﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Resources;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Common;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using GMap.NET;
using GMap.NET.MapProviders;
using GMap.NET.WindowsForms;
using GMap.NET.WindowsForms.Markers;
using Model;
using PositionServer.Service;
using TaxiDispatchClient.Properties;
using TaxiDispatchClient.Service;

namespace TaxiDispatchClient
{
    public partial class MainForm : XtraForm
    { 
        public static IPositionService PositionService;
        readonly System.Windows.Forms.Timer _timerPerf = new System.Windows.Forms.Timer();                
        readonly System.Windows.Forms.Timer _timerDrawPsg = new System.Windows.Forms.Timer();
        readonly System.Windows.Forms.Timer _timerDrawDest = new System.Windows.Forms.Timer();
        private static readonly Hashtable TaxiList = Hashtable.Synchronized(new Hashtable());
        private static readonly Hashtable PassengerList = Hashtable.Synchronized(new Hashtable());
        private static readonly Hashtable DestinationsList = Hashtable.Synchronized(new Hashtable());
        public static string UserName = string.Empty;
        public static string UserPermission = string.Empty;

        public static UserInfo MyUserInfo;


        private GMapOverlay _taxis;
        private bool _isPartRefresh;
        public static bool IsLoginOk;


        private readonly BackgroundWorker _backgroundWorker;

        private readonly DataTable _dtTaxiList = new DataTable();

        private readonly DataTable _dtPassengerList = new DataTable();

        private readonly DataTable _dtDestination = new DataTable();

        private DataRow _drCurrentClickTaxiInfo;
        private DataRow _drCurrentDestination;


        private DataTable _gridDataTable = new DataTable();

        readonly System.Media.SoundPlayer _player = new System.Media.SoundPlayer(Resources.waring);
        readonly System.Media.SoundPlayer _playersms = new System.Media.SoundPlayer(Resources.sms_received1);
        private bool _isAlarmSound = true;


        private GMapOverlay _overlay;  //用于放置公共地点标记
        private GMapOverlay _overlaySearch; 
        public static PhoneModemCom PhoneModem = new PhoneModemCom();

        private GMapOverlay _overlayOfPassenger; //用于放置乘客
        private GMapOverlay _overlayOfDestination;//用于放置目的地


        public static double ClientVersion = 1.95;

        public static MainForm MainForm1;

        public static List<string> CompanyList;
        private string _strSelectedCompany = string.Empty;

        public static List<string> BlackListOfPsg;
        private bool _isShowPrivateCar;
        private bool _isShowSpecialCar;

        private string _drawRouteType;
        private bool _isMarkerClick;


        public MainForm()
        {
            InitializeComponent();

           
           

            //byte[] arr = new byte[]{0x31,0x3F};
            //string ss = Convert.ToString(arr[1], 2).PadLeft(8, '0').Substring(4, 4);
            _backgroundWorker = new BackgroundWorker();
            _backgroundWorker.DoWork += worker_DoWork;
            _backgroundWorker.RunWorkerAsync();
            LoginForm frm = new LoginForm(this._backgroundWorker);
            frm.ShowDialog();
            //MainMap.t
            DevExpress.Data.CurrencyDataController.DisableThreadingProblemsDetection = true;
            
        }

        private void Init()
        {
            // _dtTaxiList      
            _dtTaxiList.Columns.Add("出租车牌照");
            _dtTaxiList.Columns.Add("司机号码");
            _dtTaxiList.Columns.Add("出租车状态");
            _dtTaxiList.Columns.Add("司机姓名");
            _dtTaxiList.Columns.Add("出租车车型");
            _dtTaxiList.Columns.Add("所属公司");
            _dtTaxiList.Columns.Add("经度");
            _dtTaxiList.Columns.Add("纬度");
            _dtTaxiList.Columns.Add("数据更新时间");
            _dtTaxiList.Columns.Add("IP地址");
            _dtTaxiList.Columns.Add("出租车ID");
            _dtTaxiList.Columns.Add("车辆类型");
            _dtTaxiList.Columns.Add("伤员号码");
            _dtTaxiList.Columns.Add("目的地ID");
            _dtTaxiList.Columns.Add("设备类型");

            //_dtPassengerList
            _dtPassengerList.Columns.Add("姓名");
            _dtPassengerList.Columns.Add("伤员号码");
            _dtPassengerList.Columns.Add("乘客类型");
            _dtPassengerList.Columns.Add("约定车辆手机号");
            _dtPassengerList.Columns.Add("指定车辆牌照");
            _dtPassengerList.Columns.Add("经度");
            _dtPassengerList.Columns.Add("纬度");
            _dtPassengerList.Columns.Add("目的地ID");
            _dtPassengerList.Columns.Add("呼叫时间");

            //_dtDestination
            _dtDestination.Columns.Add("Id");
            _dtDestination.Columns.Add("名称");
            _dtDestination.Columns.Add("类型");
            _dtDestination.Columns.Add("经度");
            _dtDestination.Columns.Add("纬度");            
            

            this.Text = OperateConfig.GetClientMainFormTitle()+
                "  V" +  ClientVersion.ToString("f");
            label_title.Text = OperateConfig.GetClientMainFormTitle();

            //Map
            double theCenterLat = Settings.Default.MainMapLat;
            double theCenterLng = Settings.Default.MainMapLng;

            MainMap.Manager.Mode = AccessMode.ServerAndCache;
            MainMap.MapProvider = GMapProviders.GoogleChinaMap;

            //  MainMap.MapProvider = GMapProviders.OpenStreetMap;
            _overlay = new GMapOverlay("Overlay");
            MainMap.Overlays.Add(_overlay);
            _overlaySearch = new GMapOverlay("Select");
            MainMap.Overlays.Add(_overlaySearch);            
            
            _overlayOfPassenger = new GMapOverlay("Passenger");
            MainMap.Overlays.Add(_overlayOfPassenger);

            _overlayOfDestination = new GMapOverlay("Hospital");
            MainMap.Overlays.Add(_overlayOfDestination);

            _taxis = new GMapOverlay("Taxi");
            MainMap.Overlays.Add(_taxis);
            MainMap.MaxZoom = 18;
            MainMap.MinZoom = 10;

            MainMap.Zoom = 12;
           // MainMap.Position = new PointLatLng(theCenterLat, theCenterLng);
            MainMap.Position = new PointLatLng(29.81071,114.32528);
            MainMap.DragButton = MouseButtons.Left;

            // trackBarControl_MapZoom
            trackBarControl_MapZoom.Properties.Minimum = MainMap.MinZoom;
            trackBarControl_MapZoom.Properties.Maximum = MainMap.MaxZoom;
            trackBarControl_MapZoom.Value = (int)MainMap.Zoom;

            repositoryItemCheckEdit1.CheckedChanged += new EventHandler(repositoryItemCheckEdit1_CheckedChanged);
            repositoryItemCheckEdit3.CheckedChanged += new EventHandler(repositoryItemCheckEdit3_CheckedChanged);
            repsItemCheck_showAmbulance.CheckStateChanged += new EventHandler(repsItemCheck_showAmbulance_CheckedChanged);



            _drawRouteType = OperateConfig.GetClientDrawRouteType();

          
            //CompanyUser
            foreach (string s in CompanyList)
            {
                ImageComboBoxItem item = new ImageComboBoxItem();
                item.Description = s;
                item.Value = s;               
                combox_companyList.Properties.Items.Add(item);
            }
          
            if (MyUserInfo.CompanyName != PowerConfig.MainCompanyName
                && MyUserInfo.CompanyName != "测试")
            {
                combox_companyList.Text = MyUserInfo.CompanyName;
                _strSelectedCompany = MyUserInfo.CompanyName;
                combox_companyList.Enabled = false;
            }

             
            //GetTaxis(true);
            // GetTaxiInThread
            Thread t = new Thread(GetTaxisInThread) { IsBackground = true };
            t.Start();

            Thread tGetPsgs = new Thread(GetPassengersInThread) 
            { IsBackground = true };
            tGetPsgs.Start();

            Thread tGetDest = new Thread(GetDestinationsInThread) 
            { IsBackground = true };
            tGetDest.Start();


            Thread thread = new Thread(GetOverlayInThread) { IsBackground = true };
            thread.Start();
             
            //Thread tBindCompanyList = new Thread(BindCompanyList) { IsBackground = true };            
            //tBindCompanyList.Start();

            //根据用户权限设置菜单是否可用
            SetMenuItemsEnableByPermission();
            MainForm1 = this;
             
 
        }

        private void readSmsT()
        {
            Thread.Sleep(10000);
            while (true)
            {
                try
                {
                    // ArrayList al = new ArrayList { "18602789588", "2012-02-23 11:18:00", "Hello World!" };
                    ArrayList al = PositionService.ReadSms();
                    if (al != null)
                    {
                        _playersms.Play();
                        string phoneNo = al[0].ToString();
                        string receDateTime = al[1].ToString();
                        string content = al[2].ToString();
                        BeginInvoke(new MethodInvoker(delegate()
                        {
                            SmsMessageBox s = new SmsMessageBox(phoneNo, receDateTime, content, _dtTaxiList);
                            s.Show();
                        }));

                    }
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex);
                    return;
                }


                Thread.Sleep(10000);
            }
        }


        static ReceCallForm receCallForm = new ReceCallForm();
        public void InComingTelegram()
        {
            BeginInvoke(new MethodInvoker(delegate()
                {
                    if (receCallForm != null)
                    {
                        if (receCallForm.IsDisposed)
                        {
                            receCallForm = new ReceCallForm();
                        }
                        receCallForm.Show();
                    }
                }));

        }


        public void InComingTelegram(string phoneNumber)
        {
            BeginInvoke(new MethodInvoker(delegate()
            {
                if (receCallForm != null)
                {
                    if (receCallForm.IsDisposed)
                    {
                        receCallForm = new ReceCallForm();
                    }

                    receCallForm.Show();
                    receCallForm.ShowPhoneNumber(phoneNumber);
                    receCallForm.Text = phoneNumber;
                }
            }));

        }

        /// <summary> 
        /// worker start 
        /// </summary> 
        /// <param name="sender"></param> 
        /// <param name="e"></param> 
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (!IsLoginOk)
            {
                Thread.Sleep(500);
                //Application.DoEvents();
            }
            Init();
        }

        public static bool InitWcfService(string ip)
        {
            try
            {
                NetTcpBinding netbinding = new NetTcpBinding(SecurityMode.None, true)
                {
                    MaxBufferPoolSize = 2147483647,
                    MaxBufferSize = 2147483647,
                    MaxReceivedMessageSize = 2147483647,
                    SendTimeout = new TimeSpan(0, 10, 18),
                    ReceiveTimeout = new TimeSpan(0, 10, 18),
                    ReliableSession = { Enabled = true, InactivityTimeout = new TimeSpan(0, 5, 0) },
                    ReaderQuotas =
                    {
                        MaxArrayLength = 2147483647,
                        MaxStringContentLength = 2147483647,
                        MaxBytesPerRead = 2147483647
                    },
                    TransferMode = TransferMode.Buffered,
                };
                netbinding.MaxConnections = 65536000;
                ChannelFactory<IPositionService> factory = new ChannelFactory<IPositionService>
                                     (netbinding, new EndpointAddress("net.tcp://" + ip + ":" + ConstParameters.WcfPort + "/PositionServices"));
                foreach (System.ServiceModel.Description.OperationDescription op in factory.Endpoint.Contract.Operations)
                {
                    System.ServiceModel.Description.DataContractSerializerOperationBehavior dataContractBehavior =
                                op.Behaviors.Find<System.ServiceModel.Description.DataContractSerializerOperationBehavior>();
                    if (dataContractBehavior != null)
                    {
                        dataContractBehavior.MaxItemsInObjectGraph = 2147483647;
                    }
                }
                PositionService = factory.CreateChannel();

            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                return false;
            }
            return true;

        }


        private void MainForm_Load(object sender, EventArgs e)
        {
            //_timerPerf
            _timerPerf.Tick += DrwaTaxiOnMap;
            _timerPerf.Enabled = true;
            _timerPerf.Interval = 1;
            _timerPerf.Start();
            if (UserName.ToLower() == "changyun")
            {
                barDockControlTop.Enabled = false;

            }
            _timerDrawPsg.Tick += DrawPassengerOnMap;
            _timerDrawPsg.Enabled = true;
            _timerDrawPsg.Interval = 1;
            _timerDrawPsg.Start();

            _timerDrawDest.Tick += DrawDestinationOnMap;
            _timerDrawDest.Enabled = true;
            _timerDrawDest.Interval = 1;
            _timerDrawDest.Start();

            //ReadSms
            //Thread readSms = new Thread(readSmsT);
            //readSms.Start();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (XtraMessageBox.Show("确定退出平台？", "警告", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                e.Cancel = true;
                return;
            }
            _timerPerf.Interval = 1000000;
            _timerPerf.Stop();

            Properties.Settings.Default.MainMapLat = MainMap.Position.Lat;
            Properties.Settings.Default.MainMapLng = MainMap.Position.Lng;
            Properties.Settings.Default.Save();
            Environment.Exit(0);
        }

        private void trackBarControl_MapZoom_Properties_ValueChanged(object sender, EventArgs e)
        {
            MainMap.Zoom = (trackBarControl_MapZoom.Value);
        }

        private void MainMap_OnMapZoomChanged()
        {
            trackBarControl_MapZoom.Value = (int)(MainMap.Zoom);
            if (_isPartRefresh)
            {
                Console.Write("sss");
                //  GetTaxis(true);
            }
        }

        
        private void MainMap_MouseClick(object sender, MouseEventArgs e)
        {
            if (_isMarkerClick)
            {                
                _isMarkerClick = false;
                return;
            }
            //地图上右键单击
            if (e.Button == MouseButtons.Right)
            {
               RectLatLng rectLatLng = MainMap.SelectedArea;
               //无选中区域
               if (rectLatLng.Lat == 0 && rectLatLng.Lng == 0)
               {
                   if (MyUserInfo.Permission.Contains("|"+
                       PowerConfig.AllowDispatchAmbulance+"|"))
                   {
                      _rightClickLatLng = MainMap.FromLocalToLatLng(e.X, e.Y);
                      popupMenu_mapRightHospital.ShowPopup(Cursor.Position);   
                   }                    
               }
            }
            else
            {
                PointLatLng point = MainMap.FromLocalToLatLng(e.X, e.Y);
                Console.WriteLine("经度："+point.Lng+"   纬度："+point.Lat);
            }

            //PointLatLng p = MainMap.Position;
            //if (aa % 2 == 0)
            //{
            //    a1 = MainMap.FromLocalToLatLng(e.X, e.Y).Lat;
            //    b1 = MainMap.FromLocalToLatLng(e.X, e.Y).Lng;
            //}
            //else
            //{
            //    a2 = MainMap.FromLocalToLatLng(e.X, e.Y).Lat;
            //    b2 = MainMap.FromLocalToLatLng(e.X, e.Y).Lng;
            //    MessageBox.Show((a2 - a1) + "," + (b2 - b1));
            //}
            //aa++;


        }

        private void DrwaTaxiOnMap(object sender, EventArgs e)
        {
            TaxiInfo temp = new TaxiInfo();
            lock (TaxiList.SyncRoot)
            {
                foreach (TaxiInfo taxiInfo in TaxiList.Values)
                {
                    temp = taxiInfo;
                    break;
                }

                if (temp != null && temp.DriverPhoneNumber != null)                
                {
                     PointLatLng point = 
                      new PointLatLng(temp.Latitude, temp.Longitude);
                    //cdma
                     //if (temp.CarType == ConstParameters.CarTypeOfTaxi && temp.CarDeviceType == 1)
                     //{
                     //    double lat = 0;
                     //    double lng = 0;
                     //    CommonRoutine.TransformWGSToGCJ(temp.Latitude, temp.Longitude, out lat, out lng);
                     //    point.Lat = lat;
                     //    point.Lng = lng;
                     //}

                    lock (_taxis.Markers)
                    {
                        lock (TaxiList.SyncRoot)
                        {
                            TaxiList.Remove(temp.DriverPhoneNumber);
                        }
                        GMapMarker g =
                            _taxis.Markers.FirstOrDefault(
                                gMapMarker => gMapMarker.Tag.ToString() == temp.DriverPhoneNumber);
                        if (g != null)
                        {
                            this.BeginInvoke(new MethodInvoker(() => _taxis.Markers.Remove(g)));
                        }


                        if (temp.Speed <= 0)
                        {
                            temp.Angle = 404;
                        }
                         
                       



                        int intState = temp.TaxiState;
                        if (intState==21||intState==22||intState==23||intState==24)
                        {
                            intState = 2;
                        }
                        if (intState==20)
                        {
                            intState = 0;
                        }

                        if (temp.DriverPhoneNumber == "15972965769")
                        {
                            Console.WriteLine("状态："+intState
                            +"  方向：" +temp.Angle
                            + "  星级："+temp.StartLevel 
                            +"  速度："+temp.Speed);
                        }

                        Bitmap obj = GetTaxiBitmap(temp.CarType,intState, 
                            temp.Angle, temp.StartLevel, temp.AlarmL);
                        // ArrayList al = new ArrayList { temp.DriverPhoneNumber, temp.TaxiState };
                        string speed = temp.Speed.ToString() + " 公里/小时 ";
                        if (temp.Speed > 250)
                            speed += "(超速)";
                        string isCalling = "未通话";
                        switch (temp.IsCalling)
                        {
                            case 1:
                                isCalling = "被叫通话中...";                               
                                break;
                            case 2:
                                isCalling = "主叫通话中...";                              
                                break;
                        }
                        string tipTitle = "";
                        switch (temp.CarType)
                        {
                            case ConstParameters.CarTypeOfAmbulance:
                                tipTitle = "车辆状态：" + OperateAgreement.GetTaxiState(temp.TaxiState) +
                                           Environment.NewLine
                                           + "车速：" + speed + Environment.NewLine
                                           + "出租车司机：" + temp.DriverName + Environment.NewLine
                                           + "车牌号：" + temp.TaxiNo + Environment.NewLine
                                           + "更新时间：" + temp.UpdateTime.ToString("HH:mm:ss") +
                                           Environment.NewLine
                                           + "司机号码：" + temp.DriverPhoneNumber + Environment.NewLine
                                           //+ "软件版本号：" + temp.Version + "  " + Environment.NewLine
                                           + "病员电话：" + temp.PassengerPhoneNumber;                                
                                break;
                            default:
                                tipTitle= "出租车状态：" + OperateAgreement.GetTaxiState(temp.TaxiState) +
                                Environment.NewLine
                                + "车速：" + speed + Environment.NewLine
                                + "出租车司机：" + temp.DriverName + Environment.NewLine
                                + "车牌号：" + temp.TaxiNo + Environment.NewLine
                                + "更新时间：" + temp.UpdateTime.ToString("HH:mm:ss") +
                                Environment.NewLine
                                + "号码：" + temp.DriverPhoneNumber + Environment.NewLine
                                //+ "评分等级：" + OperateAgreement.GetTaxiStar(temp.StartLevel) +
                                //Environment.NewLine
                                + "软件版本号：" + temp.Version + "  " + Environment.NewLine
                                + "通话状态：" + isCalling + Environment.NewLine
                                + "个性签名:" + temp.Signature + Environment.NewLine;
                                break;
                        }
                        TaxiMarker gMarker = new TaxiMarker(point, obj, "")
                            {
                                ToolTipText = tipTitle,
                                ToolTipMode = MarkerTooltipMode.OnMouseOver,
                                Tag = temp.DriverPhoneNumber
                            };

                        //GMarkerGoogle gMarker = new GMarkerGoogle(point, obj)
                        //                            {
                        //                                ToolTipText = tipTitle,
                        //                                ToolTipMode = MarkerTooltipMode.OnMouseOver,
                        //                                Tag = temp.DriverPhoneNumber
                        //                            };
                        gMarker.ToolTip.Format.Alignment = StringAlignment.Near;               
                        if (temp.AlarmL > 0)
                        {
                            gMarker.ToolTipText = gMarker.ToolTipText + "告警内容：" +
                                                  OperateAgreement.GetTaxiAlarmCotent(temp.AlarmL);
                            if (_isAlarmSound)
                            {
                                _player.Play();
                            }
                        }
                        if (temp.CarType==ConstParameters.CarTypeOfPrivate)
                        {
                            gMarker.IsVisible = _isShowPrivateCar;
                        }
                        if (temp.CarType == ConstParameters.CarTypeOfAmbulance)
                        {
                            gMarker.IsVisible = _isShowSpecialCar;
                        }

                        this.BeginInvoke(new MethodInvoker(() => _taxis.Markers.Add(gMarker)));
                         
                    }
                             
                }
            }


        }

        private void DrawPassengerOnMap(object sender, EventArgs e)
        {
            PassengerInfo temp = new PassengerInfo();
            lock (PassengerList.SyncRoot)
            {
                foreach (PassengerInfo psgInfo in PassengerList.Values)
                {
                    temp = psgInfo;
                    break;
                }

                if (temp != null && temp.PhoneNumber != null)
                {
                    lock (_overlayOfPassenger.Markers)
                    {
                        lock (PassengerList.SyncRoot)
                        {
                            PassengerList.Remove(temp.PhoneNumber);
                        }
                        //清除乘客图标
                        GMapMarker oldMarker =
                            _overlayOfPassenger.Markers.FirstOrDefault(
                                gMapMarker => gMapMarker.Tag.ToString() == temp.PhoneNumber);
                        if (oldMarker != null)
                        {
                            this.BeginInvoke(new MethodInvoker(() =>
                                _overlayOfPassenger.Markers.Remove(oldMarker)));
                        }
                        //清除乘客与司机间的路线
                        GMapRoute oldRoute = _overlayOfPassenger.Routes.FirstOrDefault(
                            route => route.Name == temp.PhoneNumber);
                        if (oldRoute!=null)
                        {
                            this.BeginInvoke(new MethodInvoker(() =>
                               _overlayOfPassenger.Routes.Remove(oldRoute)));
                        }
                        //清除乘客与目的地之间的路线
                        for (int i = 0; i < 3; i++)
                        {
                            GMapRoute oldRouteDest = _overlayOfDestination.Routes.FirstOrDefault(
                            route => route.Name == temp.PhoneNumber);

                            if (oldRouteDest != null)
                            {
                                this.BeginInvoke(new MethodInvoker(() =>
                                   _overlayOfDestination.Routes.Remove(oldRouteDest)));
                            }
                        }
                        

                        PointLatLng point = new PointLatLng(temp.Lat,temp.Lng);
                        Bitmap obj = TaxiState.wounded_1;
                        if (temp.Name==null)
                        {
                            temp.Name = "";
                        }
                        WoundedMarker gMarker = new WoundedMarker(point, obj,
                            temp.Name)
                        {
                            ToolTipText =
                         "伤员信息" + Environment.NewLine
                         +"姓名："+temp.Name+Environment.NewLine
                         + "伤员电话：" + temp.PhoneNumber + Environment.NewLine
                         + "约定救护车手机号：" + temp.CarPhoneNumber + Environment.NewLine
                         + "伤员所在位置经度：" + temp.Lng + Environment.NewLine
                         + "伤员所在位置纬度：" + temp.Lat + Environment.NewLine
                         + "呼叫车辆时间：" + temp.UpdateTime,                        
                         Tag = temp.PhoneNumber,
                         ToolTipMode = MarkerTooltipMode.OnMouseOver
                        };

                        //if (_drCurrentPassenger != null
                        //  && temp.PhoneNumber ==
                        //  _drCurrentPassenger["乘客号码"].ToString())
                        //{
                        //    gMarker.ToolTipText += Environment.NewLine+
                        //        "请点击指定救护车！";
                        //   // gMarker.ToolTipMode = MarkerTooltipMode.Always;
                        //}
                         
                        gMarker.ToolTip.Format.Alignment = StringAlignment.Near;
                        _overlayOfPassenger.Markers.Add(gMarker);
                        //if (string.IsNullOrEmpty(temp.CarPhoneNumber))
                        //{
                        //    Thread tlight = new Thread(LightMarker);
                        //    tlight.IsBackground = true;
                        //    tlight.Start(gMarker);
                        //}

                        
                          
                        if (!string.IsNullOrEmpty(temp.CarPhoneNumber))
                        {
                            //重绘乘客与车之间的线路
                            GMapMarker taxiMarker = _taxis.Markers.FirstOrDefault(taxi => 
                                taxi.Tag.ToString() ==temp.CarPhoneNumber);
                            if (taxiMarker!=null)
                            {
                                GMapRoute r = DrawrouteBetweenTowPoint(
                                    gMarker.Position, taxiMarker.Position,
                                    _overlayOfPassenger, temp.PhoneNumber);
                            }
                        }
                        //重绘乘客与目的地之间的线路
                        DataTable dtDest = _dtDestination.Copy();
                        DataRow[] drDest = dtDest.Select("Id='" +
                        temp.DestinationId+"'");
                        if (drDest.Length > 0)
                        {
                            double lat = double.Parse(drDest[0]["纬度"].ToString());
                            double lng = double.Parse(drDest[0]["经度"].ToString());
                            DrawrouteBetweenTowPoint(point, new PointLatLng(lat, lng),
                            _overlayOfDestination, temp.PhoneNumber);
                        }                                
                    }

                }
            }
        }

        private void DrawDestinationOnMap(object sender, EventArgs e)
        {
            DestinationInfo temp = new DestinationInfo();
            lock (DestinationsList.SyncRoot)
            {
                foreach (DestinationInfo destInfo in DestinationsList.Values)
                {
                    temp = destInfo;
                    break;
                }

                if (temp != null && temp.Id != 0)
                {
                    lock (_overlayOfDestination.Markers)
                    {
                        lock (DestinationsList.SyncRoot)
                        {
                            DestinationsList.Remove(temp.Id);
                        }
                        GMapMarker oldMarker =
                            _overlayOfDestination.Markers.FirstOrDefault(
                                gMapMarker => gMapMarker.Tag.ToString() 
                                    == temp.Id.ToString());
                        if (oldMarker != null)
                        {
                            this.BeginInvoke(new MethodInvoker(() =>
                                _overlayOfDestination.Markers.Remove(oldMarker)));
                        }
                        
                        PointLatLng point = new PointLatLng(temp.Lat, temp.Lng);
                        Bitmap obj = TaxiState.hospital_1;

                        //GMarkerGoogle gMarker = new GMarkerGoogle(point, obj)
                        //{
                        //    ToolTipText =
                        // "目的地信息" + Environment.NewLine
                        // + "名称：" + temp.Name + Environment.NewLine
                        // + "类型：" + temp.Type + Environment.NewLine
                        // + "伤员所在位置经度：" + temp.Lng + Environment.NewLine
                        // + "伤员所在位置纬度：" + temp.Lat + Environment.NewLine,                        
                        //    Tag = temp.Id,
                        //    ToolTipMode = MarkerTooltipMode.OnMouseOver
                        //};
                        string markerTitle = temp.Name;
                        if (string.IsNullOrEmpty(temp.Name))
                        {
                            markerTitle = " ";
                        }
                        HospitalMarker gMarker = new HospitalMarker(point, obj,
                            markerTitle)
                        {
                            ToolTipText =
                         "目的地信息" + Environment.NewLine
                         + "名称：" + temp.Name + Environment.NewLine
                       //  + "类型：" + temp.Type + Environment.NewLine
                         + "经度：" + temp.Lng + Environment.NewLine
                         + "纬度：" + temp.Lat + Environment.NewLine,
                            Tag = temp.Id,
                            ToolTipMode = MarkerTooltipMode.OnMouseOver
                        };
                         
                        gMarker.ToolTip.Format.Alignment = StringAlignment.Near;
                        _overlayOfDestination.Markers.Add(gMarker);
                         
                    }

                }
            }
        }



        public static Bitmap GetTaxiBitmap(int carType,int state, 
            int angle, int star, int alarmL = 0)
        {
            int name_1;    //车类型
            int name_2;   //状态
            int name_3;   //方向
            int name_4; //星级

            name_1 = carType;
            //若是未知类型则认为是出租车
            if (name_1 == 0)
            {
                name_1 = 1;
            }

            if (alarmL > 0)
            {
                name_2 = 4;
            }
            else
            {
                name_2 = state;
            }

            if ((angle >= 0 && angle <= 20) || (angle >= 340 && angle <= 360))
            {
                name_3 = 1;
            }
            else if (angle > 20 && angle < 70)
            {
                name_3 = 2;
            }
            else if (angle >= 70 && angle <= 110)
            {
                name_3 = 3;
            }
            else if (angle > 110 && angle < 160)
            {
                name_3 = 4;
            }
            else if (angle >= 160 && angle <= 200)
            {
                name_3 = 5;
            }
            else if (angle > 200 && angle < 250)
            {
                name_3 = 6;
            }
            else if (angle >= 250 && angle <= 290)
            {
                name_3 = 7;
            }
            else if (angle > 290 && angle < 340)
            {
                name_3 = 8;
            }
            else
            {
                name_3 = 9;
            }

            if (star >= 5)
                star = 5;
            if (star <= 1)
                star = 1;
            if (carType==3 || carType == 4)
            {
                //私家车、救护车暂时无等级评分
                star = 0;
            }
            //救护车暂时只有一个状态
            if (carType==4)
            {
                name_2 = 0;
            }
            name_4 = star;             
            string name = "_"+name_1+ name_2 + name_3 + name_4;
            Bitmap obj =(Bitmap)TaxiState.ResourceManager.GetObject(name);
            if (obj==null)
            {
                Console.WriteLine("？？？？？？？？？");
                obj = TaxiState._1094;
            }
            return obj;
        }

        public static Bitmap GetTaxiBitmap(int devicetype, int alarmL = 0)
        {

            Bitmap obj = null;
            if (alarmL > 0)
            {
                return TaxiState._1495;                
            }
            if (devicetype == 0)
            {
                obj = TaxiState._1095;
            }
            else if (devicetype == 1)
            {
                obj = TaxiState._1195;
            }
            else if (devicetype == 2)
            {
                obj = TaxiState._1295;
            }
            else if (devicetype == 3)
            {
                obj = TaxiState._1395;
            }
            return obj;
        }

        private bool isFirstGet = true;
        private void GetTaxisInThread()
        {
            //Thread.Sleep(10000);
            while (true)
            {
                if (TaxiList.Count == 0)
                {
                    GetTaxis(isFirstGet);
                }
                Thread.Sleep(100);
                isFirstGet = false;
            }
        }

        private void GetPassengersInThread()
        {
            //Thread.Sleep(10000);
            while (true)
            {
                if (TaxiList.Count == 0 && _isShowSpecialCar)
                {
                    GetPassengers(isFirstGet);
                }
                Thread.Sleep(100);
                isFirstGet = false;
            }
        }

        private void GetDestinationsInThread()
        {
            //Thread.Sleep(10000);
            while (true)
            {
                if (TaxiList.Count == 0 && _isShowSpecialCar)
                {
                    GetDestinations(isFirstGet);
                }
                Thread.Sleep(100);
                isFirstGet = false;
            }
        }


        private void GetTaxis(bool binding = false)
        {

            #region

          

            // lock (TaxiList.SyncRoot)
           
            try
            {
                Console.WriteLine(DateTime.Now.ToString() + "  get taxiInfos.Count");

                List<TaxiInfo> taxiInfos;
                if (_isPartRefresh)
                {
                    int zoomPower = (int)MainMap.Zoom - 10;
                    double distance = 80.0f / (Math.Pow(2, zoomPower));
                    if (_strSelectedCompany == string.Empty)
                    {
                        taxiInfos = PositionService.GetNearbyGps(MainMap.Position.Lng, MainMap.Position.Lat, distance, Common.ConstParameters.TypeTaxiDispatchClient);    
                    }                    
                    else
                    {
                        taxiInfos = PositionService.GetNearbyGpsByCompany
                            (MainMap.Position.Lng, MainMap.Position.Lat, distance,
                            ConstParameters.TypeTaxiDispatchClient,
                            _strSelectedCompany);    
                    }
                }
                else
                {
                    if (_strSelectedCompany == string.Empty)
                    {
                        taxiInfos = PositionService.GetAllTaxiInfos();
                    }
                    else
                    {
                        taxiInfos = PositionService.GetAllTaxiInfosByCompany(_strSelectedCompany);
                    }
                }
                Console.WriteLine(DateTime.Now.ToString() + "   taxiInfos.Count===" + taxiInfos.Count.ToString());

                lock (TaxiList.SyncRoot)
                {
                    TaxiList.Clear();

                    //GC.Collect();
                    _dtTaxiList.Clear();

                    foreach (TaxiInfo taxiInfo in taxiInfos)
                    {
                        //if (taxiInfo.CarType == ConstParameters.CarTypeOfTaxi && taxiInfo.CarDeviceType == 1)
                        //{
                        //    double lat = 0;
                        //    double lng = 0;
                        //    CommonRoutine.TransformWGSToGCJ(taxiInfo.Latitude, taxiInfo.Longitude, out lat, out lng);
                        //    taxiInfo.Latitude = lat;
                        //    taxiInfo.Longitude = lng;
                        //}

                        TaxiList[taxiInfo.DriverPhoneNumber] = taxiInfo;
                        DataRow dr = _dtTaxiList.NewRow();
                        string alarmL = string.Empty;
                        if (taxiInfo.AlarmL > 0)
                        {
                            alarmL = "（有告警）";
                        }
                        dr["司机姓名"] = taxiInfo.DriverName;
                        dr["出租车牌照"] = taxiInfo.TaxiNo;
                        dr["司机号码"] = taxiInfo.DriverPhoneNumber;
                        dr["出租车状态"] = alarmL + OperateAgreement.GetTaxiState(taxiInfo.TaxiState);
                        dr["出租车车型"] = taxiInfo.TaxiType;
                        dr["经度"] = taxiInfo.Latitude;
                        dr["纬度"] = taxiInfo.Longitude;
                        dr["所属公司"] = taxiInfo.CompanyName;
                        dr["数据更新时间"] = taxiInfo.UpdateTime.ToString("HH:mm:ss");
                        dr["IP地址"] = taxiInfo.Ip;
                        dr["出租车ID"] = taxiInfo.Id;

                        dr["车辆类型"] = taxiInfo.CarType;
                        dr["伤员号码"] = taxiInfo.PassengerPhoneNumber;
                        dr["目的地ID"] = taxiInfo.DestinationId;
                        dr["设备类型"] = taxiInfo.CarDeviceType;
                        _dtTaxiList.Rows.Add(dr);
                    }
                    //清理出租车图标
                    List<GMapMarker> delTaxiMarkers = new List<GMapMarker>();
                    foreach (GMapMarker gMapMarker in _taxis.Markers)
                    {
                        if (!TaxiList.Contains(gMapMarker.Tag.ToString()))
                        {
                            delTaxiMarkers.Add(gMapMarker);
                        }
                    }

                    if (delTaxiMarkers.Count > 0)
                    {
                        foreach (GMapMarker gMapMarker in delTaxiMarkers)
                        {
                            GMapMarker marker = gMapMarker;
                            this.BeginInvoke(new MethodInvoker(() => _taxis.Markers.Remove(marker)));                          
                        }
                         
                        delTaxiMarkers.Clear();
                    }
                    ////清理乘客图标
                    //List<GMapMarker> delPsgerMarkers = new List<GMapMarker>();
                    //foreach (GMapMarker gmarker in _overlayOfRoute.Markers)
                    //{
                    //    if (!TaxiList.Contains(gmarker.Tag.ToString()))
                    //    {
                    //        delPsgerMarkers.Add(gmarker);
                    //    }
                    //}
                    //if (delPsgerMarkers.Count > 0)
                    //{
                    //    foreach (GMapMarker gMapMarker in delPsgerMarkers)
                    //    {
                    //        GMapMarker marker = gMapMarker;
                    //        this.BeginInvoke(new MethodInvoker(() =>
                    //        _overlayOfRoute.Markers.Remove(marker)));
                    //    }                        
                    //}
                    ////清理乘客之间的路线
                    //List<GMapRoute> delRoutes = new List<GMapRoute>();
                    //foreach (GMapRoute route in _overlayOfRoute.Routes)
                    //{
                    //    if (!TaxiList.Contains(route.Name))                        
                    //    {
                    //        delRoutes.Add(route);
                    //    }
                    //}
                    //if (delRoutes.Count > 0)
                    //{
                    //    foreach (GMapRoute route in delRoutes)
                    //    {
                    //        GMapRoute delroute = route;
                    //        this.BeginInvoke(new MethodInvoker(() =>
                    //        _overlayOfRoute.Routes.Remove(delroute)));
                    //    }                    
                    //}
                }
              
                if (_strSelectedCompany!="")
                {
                    DataSet ds = PositionService.DriverGetList(
                        "CompanyName like '" + _strSelectedCompany + "%'");
                    if (ds!=null && ds.Tables.Count!=0)
                    {
                        foreach (DataRow dataRow in ds.Tables[0].Rows)
                        {
                            
                            if (_dtTaxiList.Select("出租车牌照='" +
                                    dataRow["TaxiNo"] + "'").Length==0)
                            {
                                DataRow dr = _dtTaxiList.NewRow();
                                dr["司机姓名"] = dataRow["name"].ToString();
                                dr["出租车牌照"] = dataRow["TaxiNo"].ToString();
                                dr["司机号码"] = dataRow["phoneNumber"].ToString();
                                dr["出租车状态"] = "未上线";
                                dr["出租车车型"] = "";
                                dr["经度"] = "0";
                                dr["纬度"] = "0";
                                dr["所属公司"] = _strSelectedCompany;
                                dr["数据更新时间"] = "";
                                dr["IP地址"] = "";
                                dr["出租车ID"] = dataRow["taxiid"].ToString();
                                dr["车辆类型"] = "1";
                                dr["设备类型"] = "0";
                                _dtTaxiList.Rows.Add(dr);    
                            }                            
                        }    
                    }
                    //DataSet ds = PositionService(
                    //   "CompanyName like '" + _strSelectedCompany + "%'");
                    //if (ds != null && ds.Tables.Count != 0)
                    //{
                    //    foreach (DataRow dataRow in ds.Tables[0].Rows)
                    //    {

                    //        if (_dtTaxiList.Select("出租车牌照='" +
                    //                dataRow["TaxiNo"] + "'").Length == 0)
                    //        {
                    //            DataRow dr = _dtTaxiList.NewRow();
                    //            dr["司机姓名"] = dataRow["name"].ToString();
                    //            dr["出租车牌照"] = dataRow["TaxiNo"].ToString();
                    //            dr["司机号码"] = dataRow["phoneNumber"].ToString();
                    //            dr["出租车状态"] = "未上线";
                    //            dr["出租车车型"] = "";
                    //            dr["经度"] = "0";
                    //            dr["纬度"] = "0";
                    //            dr["所属公司"] = _strSelectedCompany;
                    //            dr["数据更新时间"] = "";
                    //            dr["IP地址"] = "";
                    //            dr["出租车ID"] = dataRow["taxiid"].ToString();
                    //            dr["车辆类型"] = "1";
                    //            _dtTaxiList.Rows.Add(dr);
                    //        }
                    //    }
                    //}
                    
                }


                if (gridView1.RowCount == 0)
                {
                   
                    this.BeginInvoke(new MethodInvoker(() =>
                        {
                            //gridControl_TaxiList.DataSource = _dtTaxiList.Copy();

                            DataTable dtsource = GetGridBindDt();
                            gridControl_TaxiList.DataSource = dtsource;

                            if (_strSelectedCompany != "")
                            {
                                int count = dtsource.Select("出租车状态 = '" + "未上线" + "'").Length;
                                int online = dtsource.Rows.Count - count;
                                gridView1.GroupPanelText = "本公司一共" + dtsource.Rows.Count
                                    + "辆车 当前在线" + online + "辆";
                            }
                            else
                            {
                                gridView1.GroupPanelText = "当前一共" + dtsource.Rows.Count + "辆出租车.";
                            }

                            // gridView1.Columns["出租车牌照"].Width = 200;
                           // gridView1.GroupPanelText = "当前一共" + gridView1.RowCount + "辆出租车.";
                        }));
                }
             
                
            }
            catch (Exception ex)
            {
                //Console.WriteLine("网络不稳定，获取服务器数据失败。请重新登录。");
                XtraMessageBox.Show("网络不稳定，获取服务器数据失败。请重新登录。");
                CommonRoutine.HandlingExceptions(ex);
                Environment.Exit(0);
            }

            #endregion



            if (binding)
            {
                this.Invoke(new MethodInvoker(delegate()
                    {
                        _gridDataTable.Clear();
                        //_gridDataTable = _dtTaxiList.Copy();
                        _gridDataTable = GetGridBindDt();
                        gridControl_TaxiList.DataSource = _gridDataTable;
                       // gridView1.Columns["出租车牌照"].Width = 200;

                        searchLookUpEdit1.Properties.DataSource = _gridDataTable;

                        if (_strSelectedCompany != "")
                        {
                            int count = _gridDataTable.Select("出租车状态 = '" + "未上线" + "'").Length;
                            int online = _gridDataTable.Rows.Count - count;
                            gridView1.GroupPanelText = "本公司一共" + _gridDataTable.Rows.Count
                                + "辆车 当前在线" + online + "辆";
                        }
                        else
                        {
                            gridView1.GroupPanelText = "当前一共" + _gridDataTable.Rows.Count + "辆出租车.";
                        }
                          
                        _taxis.Markers.Clear();

                        //gridcontrolTaxiList
                        gridView1.Columns[0].Width = 80;
                        gridView1.Columns[0].AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                        gridView1.Columns[0].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                        gridView1.Columns[1].Width = 88;
                        gridView1.Columns[1].AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                        gridView1.Columns[1].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                        gridView1.Columns[2].Width = 108;
                    }));

            }
            else
            {
                if (barEditItem_refreshTime.EditValue == null)
                {
                    barEditItem_refreshTime.EditValue = 30;
                }
                int refreshtime;
                int.TryParse(barEditItem_refreshTime.EditValue.ToString(), out refreshtime);
                if (refreshtime < 5)
                {
                    refreshtime = 5;
                }
                Thread.Sleep(refreshtime * 1000);
            }


        }

        private void GetPassengers(bool binding = false)
        {

            #region
             
            // lock (TaxiList.SyncRoot)

            try
            {
                Console.WriteLine(DateTime.Now.ToString() + "  get passenger.Count");

                List<PassengerInfo> passengers;
                if (_isPartRefresh)
                {
                    int zoomPower = (int)MainMap.Zoom - 10;
                    double distance = 80.0f / (Math.Pow(2, zoomPower));                
                    
                    passengers = PositionService.GetNearbyPassengerByCarType(
                            MainMap.Position.Lng, MainMap.Position.Lat, distance, 
                            ConstParameters.TypeTaxiDispatchClient,
                            "|"+ConstParameters.CarTypeOfAmbulance+"|");                     
                }
                else
                {
                    passengers = PositionService.GetAllPassengerByCarType(
                        ConstParameters.TypeTaxiDispatchClient,
                        "|" + ConstParameters.CarTypeOfAmbulance + "|");
                     
                }
                Console.WriteLine(DateTime.Now.ToString() +
                    "   passengers.Count===" + passengers.Count.ToString());

                lock (PassengerList.SyncRoot)
                {
                    PassengerList.Clear();

                    //GC.Collect();
                    _dtPassengerList.Clear();

                    foreach (PassengerInfo psgInfo in passengers)
                    {
                        PassengerList[psgInfo.PhoneNumber] = psgInfo;
                        DataRow dr = _dtPassengerList.NewRow();
                        dr["姓名"] = psgInfo.Name;
                        dr["伤员号码"] = psgInfo.PhoneNumber;
                        dr["乘客类型"] = psgInfo.Type;
                        dr["约定车辆手机号"]=psgInfo.CarPhoneNumber;
                        dr["指定车辆牌照"] = psgInfo.CarNo;
                        dr["经度"] = psgInfo.Lng;
                        dr["纬度"] = psgInfo.Lat;
                        dr["目的地ID"] = psgInfo.DestinationId;
                        dr["呼叫时间"] = psgInfo.UpdateTime;

                        _dtPassengerList.Rows.Add(dr);
                    }

                    //清理未搜索到的乘客图标 
                    List<GMapMarker> delPsgerMarkers = new List<GMapMarker>();
                    foreach (GMapMarker gmarker in _overlayOfPassenger.Markers)
                    {
                        if (!PassengerList.Contains(gmarker.Tag.ToString()))
                        {
                            delPsgerMarkers.Add(gmarker);
                        }
                    }
                    if (delPsgerMarkers.Count > 0)
                    {
                        foreach (GMapMarker gMapMarker in delPsgerMarkers)
                        {
                            GMapMarker marker = gMapMarker;
                            this.BeginInvoke(new MethodInvoker(() =>
                            _overlayOfPassenger.Markers.Remove(marker)));
                        }
                    }
                    //清理乘客与车辆之间的路线
                    List<GMapRoute> delRoutes = new List<GMapRoute>();
                    foreach (GMapRoute route in _overlayOfPassenger.Routes)
                    {
                        if (!PassengerList.Contains(route.Name))
                        {
                            delRoutes.Add(route);
                        }
                    }
                    if (delRoutes.Count > 0)
                    {
                        foreach (GMapRoute route in delRoutes)
                        {
                            GMapRoute delroute = route;
                            this.BeginInvoke(new MethodInvoker(() =>
                            _overlayOfPassenger.Routes.Remove(delroute)));
                        }
                    }

                    //清理乘客与医院之间的路线
                    List<GMapRoute> delRoutes2 = new List<GMapRoute>();
                    foreach (GMapRoute route in _overlayOfDestination.Routes)
                    {
                        if (!PassengerList.Contains(route.Name))
                        {
                            delRoutes2.Add(route);
                        }
                    }
                    if (delRoutes2.Count > 0)
                    {
                        foreach (GMapRoute route in delRoutes2)
                        {
                            GMapRoute delroute = route;
                            this.BeginInvoke(new MethodInvoker(() =>
                            _overlayOfDestination.Routes.Remove(delroute)));
                        }
                    }
                  
                    
                }
            
            }
            catch (Exception ex)
            {
                //Console.WriteLine("网络不稳定，获取服务器数据失败。请重新登录。");
                XtraMessageBox.Show("网络不稳定，获取服务器数据失败。请重新登录。");
                CommonRoutine.HandlingExceptions(ex);
                Environment.Exit(0);
            }

            #endregion



            if (binding)
            {
                //this.Invoke(new MethodInvoker(delegate()
                //{
                //    //_gridDataTable.Clear();
                //    ////_gridDataTable = _dtTaxiList.Copy();
                //    //_gridDataTable = GetGridBindDt();
                //    //gridControl_TaxiList.DataSource = _gridDataTable;
                //    //// gridView1.Columns["出租车牌照"].Width = 200;

                  
                //}));

            }
            else
            {
                if (barEditItem_refreshTime.EditValue == null)
                {
                    barEditItem_refreshTime.EditValue = 30;
                }
                int refreshtime;
                int.TryParse(barEditItem_refreshTime.EditValue.ToString(), out refreshtime);
                if (refreshtime < 5)
                {
                    refreshtime = 5;
                }
                Thread.Sleep(refreshtime * 1000);
            }


        }

        private void GetDestinations(bool binding = false)
        {

            #region

            // lock (TaxiList.SyncRoot)

            try
            {
                Console.WriteLine(DateTime.Now.ToString() + "  get destination.Count");

                List<DestinationInfo> destinations;
                if (_isPartRefresh)
                {
                    int zoomPower = (int)MainMap.Zoom - 10;
                    double distance = 80.0f / (Math.Pow(2, zoomPower));
             
                    destinations = PositionService.GetNearbyDestinationInfo(
                        MainMap.Position.Lng, MainMap.Position.Lat, distance,                       
                        "|" + ConstParameters.CarTypeOfAmbulance + "|");                     
                }
                else
                {
                    destinations = PositionService.GetAllDestinationInfo();
                }
                Console.WriteLine(DateTime.Now.ToString() +
                    "   destinations.Count===" + destinations.Count.ToString());

                lock (DestinationsList.SyncRoot)
                {
                    DestinationsList.Clear();
 
                    _dtDestination.Clear();

                    foreach (DestinationInfo destInfo in destinations)
                    {
                        DestinationsList[destInfo.Id] = destInfo;
                        DataRow dr = _dtDestination.NewRow();
                        dr["Id"] = destInfo.Id;
                        dr["类型"] = destInfo.Type;
                        dr["名称"] = destInfo.Name;
                        dr["经度"] = destInfo.Lng;
                        dr["纬度"] = destInfo.Lat;
                        _dtDestination.Rows.Add(dr);
                    }

                    //清理未搜索到的目的地图标
                    List<GMapMarker> delDestMarkers = new List<GMapMarker>();
                    foreach (GMapMarker gmarker in _overlayOfDestination.Markers)
                    {
                        if (!DestinationsList.Contains(gmarker.Tag.ToString()))
                        {
                            delDestMarkers.Add(gmarker);
                        }
                    }
                    if (delDestMarkers.Count > 0)
                    {
                        foreach (GMapMarker gMapMarker in delDestMarkers)
                        {
                            GMapMarker marker = gMapMarker;
                            this.BeginInvoke(new MethodInvoker(() =>
                            _overlayOfDestination.Markers.Remove(marker)));
                        }
                    }                           
                }
            }
            catch (Exception ex)
            {              
                XtraMessageBox.Show("网络不稳定，获取服务器数据失败。请重新登录。");
                CommonRoutine.HandlingExceptions(ex);
                Environment.Exit(0);
            }

            #endregion
             
            if (binding)
            {
                //this.Invoke(new MethodInvoker(delegate()
                //{
                   
                //}));

            }
            else
            {
                if (barEditItem_refreshTime.EditValue == null)
                {
                    barEditItem_refreshTime.EditValue = 30;
                }
                int refreshtime;
                int.TryParse(barEditItem_refreshTime.EditValue.ToString(), out refreshtime);
                if (refreshtime < 5)
                {
                    refreshtime = 5;
                }
                Thread.Sleep(refreshtime * 1000);
            }


        }

        private void barButtonItem_TopbartaxiInfo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
           
            //  new TaxiCotrolForm(_drCurrentClickTaxiInfo).ShowDialog();
            TaxiFrom taxi = new TaxiFrom();
            taxi.ShowDialog();
        }

        private void barButtonItem_Topbardriverinfo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
          
            DriverForm driver = new DriverForm();
            driver.ShowDialog();
        }

        private void barButtonItem_TopbaruserInfo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
           
            UserForm u = new UserForm();
            u.ShowDialog();
        }

        private void barButtonItem_TopbarComplaint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
           
            ComplaintForm complaint = new ComplaintForm();
            complaint.ShowDialog();
        }

        private void barButtonItem_TopbarTeleCallFind_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            
            TradeHistoryForm tradeHistory = new TradeHistoryForm();
            tradeHistory.ShowDialog();
        }

        private void simpleButton_goto_Click(object sender, EventArgs e)
        {
            _overlaySearch.Markers.Clear();
            if (textBoxGeo.Text.Trim() == "")
            {
                //XtraMessageBox.Show("请输入想要查找的地址！");               
                textBoxGeo.Focus();
                return;
            }
            //MainMapSetCurrentPositionByKeywords(textBoxGeo.Text);
         
            int count = 0;
            foreach (DataRow dr in DtOverlayList.Rows)
            {
                string markerName = dr["OverlayName"].ToString();
                if (markerName.Contains(textBoxGeo.Text.Trim()))
                {
                    Bitmap obj = GmapOverlayManagementForm.GetMarkerBitmap(dr["Overlaytype"].ToString());
                    PointLatLng point = new PointLatLng(double.Parse(dr["Latitude"].ToString()),
                        double.Parse(dr["Longitude"].ToString()));
                    GMarkerGoogle gMarker = new GMarkerGoogle(point, obj)
                    {
                        ToolTipText = dr["OverlayName"].ToString(),
                        ToolTipMode = MarkerTooltipMode.Always
                    };
                    _overlaySearch.Markers.Add(gMarker);
                    count++;
                    if (count == 1)
                    {
                        MainMap.Position = point;
                    }
                }
            }
            if (count == 0)
            {
                MainMapSetCurrentPositionByKeywords(textBoxGeo.Text);
            }            
        }

        private void textBoxGeo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((Keys)e.KeyChar == Keys.Enter)
            {
                if (textBoxGeo.Text.Trim() == "")
                {
                    XtraMessageBox.Show("请输入想要查找的地址！");
                    textBoxGeo.Focus();
                    return;
                }
               // MainMapSetCurrentPositionByKeywords(textBoxGeo.Text);
               simpleButton_goto_Click(null,null);
            }

        }
        private void MainMapSetCurrentPositionByKeywords(string positionName)
        {
            GeoCoderStatusCode status = MainMap.SetPositionByKeywords(positionName);
            if (status != GeoCoderStatusCode.G_GEO_SUCCESS)
            {
                MessageBox.Show("谷歌地图找不到: '" + textBoxGeo.Text + "', reason: " + status.ToString(), "GMap.NET", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                if (_isPartRefresh)
                {
                    lock (TaxiList.SyncRoot)
                    {
                        TaxiList.Clear();
                    }
                    lock (_taxis.Markers)
                    {
                        _taxis.Markers.Clear();
                    }
                    GetTaxis();
                }
            }
        }

        private void searchLookUpEdit1_EditValueChanged(object sender, EventArgs e)
        {

          

            DataRow dr = searchLookUpEdit1.Properties.View.GetFocusedDataRow();
            if (dr == null) return;

            string state = dr["出租车状态"].ToString();
            if (state == "未上线")
            {
                return;
            }

            gridControl_TaxiList.DataSource = dr;
            PointLatLng p = new PointLatLng(double.Parse(dr["经度"].ToString()), double.Parse(dr["纬度"].ToString()));
            MainMap.Position = p;
        }

        private void radioGroup1_EditValueChanged(object sender, EventArgs e)
        {
            if (radioGroup1.SelectedIndex == 0)
            {
                _isPartRefresh = false;
            }
            else if (radioGroup1.SelectedIndex == 1)
            {
                _isPartRefresh = true;
            }
            //GetTaxis(true);
        }

        //
        private void simpleButton_RefreshGridview_Click(object sender, EventArgs e)
        {
            //TaxiNoPsgConfigSetForm form = new TaxiNoPsgConfigSetForm("13627264054");
            //form.ShowDialog();
            
            //Thread getTaxisT = new Thread(GetTaxisT);
            //getTaxisT.Start();
            DataTable sdt = GetGridBindDt();
            gridControl_TaxiList.DataSource = sdt;
           // gridView1.Columns["出租车牌照"].Width = 200;

            searchLookUpEdit1.Properties.DataSource = sdt;
            if (_strSelectedCompany!="")
            {
                int count = sdt.Select("出租车状态 = '" + "未上线" + "'").Length;
                int online = sdt.Rows.Count - count;
                gridView1.GroupPanelText = "本公司一共" + sdt.Rows.Count
                    + "辆车 当前在线" + online + "辆"; 
            }
            else
            {
                gridView1.GroupPanelText = "当前一共" + sdt.Rows.Count + "辆出租车.";    
            }
            //_taxis.Markers.Clear();

        }


        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {

            DataRow dr = this.gridView1.GetFocusedDataRow();//
            if (dr != null)
            {
                if (dr["出租车状态"] == "未上线")
                {
                    return;
                }

                if (e.Button == MouseButtons.Right)
                {
                    _drCurrentClickTaxiInfo = dr;

                    string carType = _drCurrentClickTaxiInfo["车辆类型"].ToString();
                    switch (carType)
                    {
                        case "1":
                            popupMenu_MouseLeft.ShowPopup(MousePosition);
                            if (UserPermission.Contains("|" + PowerConfig.CallForTaxiForm + "|"))
                            {
                                barBtn_CallForTaxiForm2.Enabled = 
                                    dr["出租车状态"].ToString() == "空载";
                            }
                            break;
                        case "3":
                            break;
                        case "4":
                            popupMenu_woundedRight.ShowPopup(MousePosition);
                            break;
                    }


                    ////当选择的是私家车时 不显示右键菜单
                    //if (_drCurrentClickTaxiInfo["车辆类型"].ToString() != "3")
                    //{
                    //    popupMenu_MouseLeft.ShowPopup(MousePosition);
                    //}
                    
                    //if (UserPermission.Contains("|" + PowerConfig.CallForTaxiForm + "|"))
                    //{                      
                    //    barBtn_CallForTaxiForm2.Enabled = dr["出租车状态"].ToString()=="空载";
                    //}
                }
                else
                {
                    PointLatLng p = new PointLatLng(double.Parse(dr["经度"].ToString()), double.Parse(dr["纬度"].ToString()));
                    MainMap.Position = p;
                }
            }
        }

        private void barButtonItem_MLTaxinfo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (_drCurrentClickTaxiInfo != null)
            {
                //string power = "|" + PowerConfig.TaxiCotrolForm + "|";
                //string permission = UserPermission;
                //if (!permission.Contains(power) && UserName != "admin")
                //{
                //    XtraMessageBox.Show("该模块无授权，不能查看！");
                //    return;
                //}
                new TaxiCotrolForm(_drCurrentClickTaxiInfo).ShowDialog();
            }
            else
            {
                XtraMessageBox.Show("该出租车信息以及不存在，请重新刷新列表");
            }
        }


        private DataRow _drCurrentPassenger;

        private void MainMap_OnMarkerClick(GMapMarker item, MouseEventArgs e)
        {
            _isMarkerClick = true;
            string markerType = item.Overlay.Id;
            if (e.Button == MouseButtons.Left)
            {
                return;
            }
            else
            {
                switch (markerType)
                {
                    case "Taxi":
                        #region
                        if (item.Tag == null) return;

                        DataTable dt = _dtTaxiList.Copy();
                        StringBuilder sb = new StringBuilder();
                        sb.Append("司机号码='");
                        sb.Append(item.Tag.ToString());
                        sb.Append("'");

                        DataRow[] drs = dt.Select(sb.ToString());
                        _drCurrentClickTaxiInfo = drs.Length >= 1 ? drs[0] : null;
                        if (_drCurrentClickTaxiInfo == null)
                        {
                            return;
                        }
                        string carType = _drCurrentClickTaxiInfo["车辆类型"].ToString();                     
                        switch (carType)
                        {
                            case "1":
                                string deviceType = _drCurrentClickTaxiInfo["设备类型"].ToString();
                                if (deviceType=="1")//CDMA类型
                                {
                                    return;
                                }
                                popupMenu_MouseLeft.ShowPopup(MousePosition);
                                if (UserPermission.Contains("|" + PowerConfig.CallForTaxiForm + "|"))
                                {
                                    barBtn_CallForTaxiForm2.Enabled = drs[0]["出租车状态"].ToString() == "空载";
                                }
                                break;
                            case "3":
                                break;
                            case "4":

                                if (MyUserInfo.Permission.Contains("|" +
                                 PowerConfig.AllowDispatchAmbulance + "|"))
                                {
                                    popupMenu_ambulanceRight.ShowPopup(MousePosition); 
                                }                                            
                                break;
                        }
                        break;
                        #endregion

                    case "Passenger":
                        #region

                        if (item.Tag == null) return;
                        DataTable dtPsg = _dtPassengerList.Copy();
                        StringBuilder sbPsg = new StringBuilder();
                        sbPsg.Append("伤员号码='");
                        sbPsg.Append(item.Tag.ToString());
                        sbPsg.Append("'");

                        DataRow[] drsPsg = dtPsg.Select(sbPsg.ToString());
                        _drCurrentPassenger = drsPsg.Length >=
                            1 ? drsPsg[0] : null;

                        if (_drCurrentPassenger == null)
                        {
                            return;
                        }
                        if (MyUserInfo.Permission.Contains("|" +
                               PowerConfig.AllowDispatchAmbulance + "|"))
                        {
                            popupMenu_woundedRight.ShowPopup(MousePosition);    
                        }     
                         
                        #endregion
                        break;
                    case "Hospital":

                        #region
                        if (item.Tag == null) return;
                        DataTable dtDest = _dtDestination.Copy();
                        StringBuilder sbDest = new StringBuilder();
                        sbDest.Append("Id='");
                        sbDest.Append(item.Tag.ToString());
                        sbDest.Append("'");
                        DataRow[] drsDest = dtDest.Select(sbDest.ToString());
                        _drCurrentDestination = drsDest.Length >=
                            1 ? drsDest[0] : null;

                        if (_drCurrentDestination == null)
                        {
                            return;
                        }
                        if (MyUserInfo.Permission.Contains("|" +
                             PowerConfig.AllowDispatchAmbulance + "|"))
                        {
                            popupMenu_hospitalRight.ShowPopup(MousePosition);   
                        }                             
                        #endregion
                        break;
                }
            }
            
        }

        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            
            AudioMgrForm audioMgrForm = new AudioMgrForm();
            audioMgrForm.ShowDialog();
        }

        private void barButtonItem_topbarimages_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
           
            ImageForm imgform = new ImageForm();
            imgform.ShowDialog();
        }


        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
           
            TaxiSetRectForm taxiSetRectForm = new TaxiSetRectForm();
            taxiSetRectForm.ShowDialog();
        }


        private void barButtonItem5_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
           
            TaxiGPSHistoryForm taxiGpsHistoryForm = new TaxiGPSHistoryForm();
            taxiGpsHistoryForm.ShowDialog();
        }

        private void barButtonItem6_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
          
            TaxiGroupForm taxiGroupForm = new TaxiGroupForm();
            taxiGroupForm.ShowDialog();

        }

        private void barButtonItem7_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
           
            CallForTaxiForm callForTaxiForm = new CallForTaxiForm(_dtTaxiList);
            callForTaxiForm.ShowDialog();
        }

        private void barButtonItem8_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
          
            TransferServerIPSetForm transfer = new TransferServerIPSetForm();
            transfer.ShowDialog();
        }

        private void barButtonItem10_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
          
            ComplaintForm complaintForm = new ComplaintForm();
            complaintForm.ShowDialog();
        }

        private void barButtonItem11_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
          
            ComplaintToUsersForm complaintToUsers = new ComplaintToUsersForm();
            complaintToUsers.ShowDialog();
        }

        //
        private void barButtonItem12_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (_isAlarmSound)
            {
                _isAlarmSound = false;
                btnSoundAlarmicon.Glyph = Resources.sound_off_icon;
                btnSoundAlarmicon.Caption = "打开告警声音";
            }
            else
            {
                _isAlarmSound = true;
                btnSoundAlarmicon.Glyph = Resources.sound_icon;
                btnSoundAlarmicon.Caption = "关闭告警声音";

            }
        }

        private void barButtonItem12_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            
            TaxiStateStatisticsReportForm reportForm = new TaxiStateStatisticsReportForm();
            reportForm.ShowDialog();
        }


        private void barBtnItem_TaxiOfCdmaForm_ItemClick(object sender, ItemClickEventArgs e)
        {
            TaxiOfCdmaForm cdmaForm = new TaxiOfCdmaForm();
            cdmaForm.ShowDialog();
        }


      
        private void combox_companyList_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = combox_companyList.SelectedIndex;
            if (index <= 0)
            {
                _strSelectedCompany = string.Empty;
            }
            else
            {
                _strSelectedCompany = combox_companyList.Properties.Items[
                    index].Description;
            }
            lock (TaxiList.SyncRoot)
            {
                TaxiList.Clear();
                _taxis.Markers.Clear();
                _dtTaxiList.Clear();
                gridControl_TaxiList.DataSource = null;
                gridView1.GroupPanelText = "正在重新获取出租车请稍等......";
            }


        }


        #region publicPlace

        public static DataTable DtOverlayList = new DataTable();

        private void GetOverlayInThread()
        {
            while (true)
            {
                string  strWhere = "City = " + MyUserInfo.CompanyId;
                
                DataSet ds = PositionService.GmapoverlayGetList(strWhere);
                if (ds!=null && ds.Tables.Count>0)
                {
                   DtOverlayList = ds.Tables[0];    
                }                
                if (DtOverlayList.Rows.Count > 0)
                {
                    break;
                }
                Thread.Sleep(10000);
            }
        }

        private void barButtonItem13_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            
            GmapOverlayManagementForm gmapOverlay = new GmapOverlayManagementForm();
            gmapOverlay.ShowDialog();          
        }
 

        private void AddMarkerToOverlay(DataRow row)
        {
            if (row == null) return;
            Bitmap obj = GmapOverlayManagementForm.GetMarkerBitmap(row["Overlaytype"].ToString());
            PointLatLng point = new PointLatLng(double.Parse(row["Latitude"].ToString()),
                double.Parse(row["Longitude"].ToString()));
            GMarkerGoogle gMarker = new GMarkerGoogle(point, obj)
            {
                ToolTipText = row["OverlayName"].ToString(),
                //Tag = row["OverlayName"].ToString()
                //row["OverlayName"] + Environment.NewLine +
                //"星级：" + row["Star"] + Environment.NewLine + "备注：" + row["Remark"],
                //ToolTipMode = MarkerTooltipMode.OnMouseOver
                //Tag = row["id"] 
            };

            if (barEditItem_showMarkerTip.EditValue != null &&
                barEditItem_showMarkerTip.EditValue.ToString() == "True")
                gMarker.ToolTipMode = MarkerTooltipMode.Always;
            _overlay.Markers.Add(gMarker);
            
        }
        #endregion


        private void barButtonItem_PlusNews_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {          
            NewsPushForm newsPush = new NewsPushForm(_dtTaxiList);
            newsPush.ShowDialog();
        }

        private void repositoryItemCheckEdit1_CheckedChanged(object sender, EventArgs e)
        {
            CheckEdit checkEdit = sender as CheckEdit;
            if (checkEdit != null)
            {
                if (checkEdit.Checked)
                {
                    try
                    {
                        _overlay.Markers.Clear();
                        for (int i = 0; i < DtOverlayList.Rows.Count; i++)
                        {
                            AddMarkerToOverlay(DtOverlayList.Rows[i]);
                        }

                        //DtOverlayList.Clear();

                        _overlay.IsVisibile = true;
                    }
                    catch (Exception ex)
                    {
                        CommonRoutine.HandlingExceptions(ex);
                    }
                }
                else
                {
                    _overlay.IsVisibile = false;

                }
            }
        }

        private void repositoryItemCheckEdit3_CheckedChanged(object sender, EventArgs e)
        {
            CheckEdit checkEdit = sender as CheckEdit;
            if (checkEdit != null)
            {
                  try
                  {
                      barEditItem_showPrivateCar.Enabled = false;
                    DataTable dt = _dtTaxiList.Copy();
                    List<string> privateList = new List<string>();
                      
                    foreach (DataRow row in dt.Rows)
                    {
                        int cartype = int.Parse(row["车辆类型"].ToString());
                        string phone = row["司机号码"].ToString();
                        if (cartype == ConstParameters.CarTypeOfPrivate)
                        {
                            privateList.Add(phone);
                        }
                    }
               
                    if (checkEdit.Checked)
                    {
                        _isShowPrivateCar = true;                                    
                        lock (_taxis.Markers)
                        {
                            foreach (GMarkerGoogle marker in _taxis.Markers)
                            {
                                if (privateList.Contains(marker.Tag.ToString()))
                                {
                                    marker.IsVisible = false;
                                }
                            }
                        }
                   
                    }
                    else
                    {
                        _isShowPrivateCar = false;
                        lock (_taxis.Markers)
                        {
                            foreach (GMarkerGoogle marker in _taxis.Markers)
                            {
                                if (privateList.Contains(marker.Tag.ToString()))
                                {
                                    marker.IsVisible = false;
                                }
                            }
                        }
                    }
                 }
                  catch (Exception ex)
                  {
                      CommonRoutine.HandlingExceptions(ex);
                      barEditItem_showPrivateCar.Enabled = true;
                  }
                  barEditItem_showPrivateCar.Enabled = true;
            }
        }

        private void repsItemCheck_showAmbulance_CheckedChanged(object sender, EventArgs e)
        {
            CheckEdit checkEdit = sender as CheckEdit;
            if (checkEdit != null)
            {
                if (checkEdit.Checked)
                {
                    try
                    {
                        _isShowSpecialCar = true;
                        _overlayOfPassenger.IsVisibile = true;
                        _overlayOfDestination.IsVisibile = true;
                    }
                    catch (Exception ex)
                    {
                        CommonRoutine.HandlingExceptions(ex);
                    }
                }
                else
                {
                    _isShowSpecialCar = false;
                    _overlayOfPassenger.IsVisibile = false;
                    _overlayOfDestination.IsVisibile = false;
                }
            }
        }


        private void barBtnItem_phoneuser_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
           
            PhoneUserForm phoneUser = new PhoneUserForm();
            phoneUser.ShowDialog();
        }

        private void barButtonItem15_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
          
            CallRecordsForm callRecordsForm = new CallRecordsForm();
            callRecordsForm.ShowDialog();
        }

        private void barButtonItem16_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            TaxiWarmingHistoryForm warmingHistory = new TaxiWarmingHistoryForm();
            warmingHistory.ShowDialog();
        }

        private void barButtonItem17_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
          
            RoleManagementForm roleManagement = new RoleManagementForm();
            roleManagement.ShowDialog();
        }

        private void barButtonItem18_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //断油
            if (XtraMessageBox.Show("确定向该出租车发送断油命令？", "警告：", MessageBoxButtons.YesNo)
                == DialogResult.Yes)
            {
                bool isOK = false;
                if (_drCurrentClickTaxiInfo != null)
                {
                    isOK = SendData(ConstParameters.CmdTaxiCutOil, new byte[1], _drCurrentClickTaxiInfo["司机号码"].ToString());
                }
                XtraMessageBox.Show(isOK ? "断油命令发送成功！" : "断油命令发送失败！");
            }
        }

        private bool SendData(ushort messageId, byte[] messageBody, string phoneNum)
        {
            try
            {
                string transferServerIp = OperateConfig.GetClientTransferServerIp();
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ipAddress = IPAddress.Parse(transferServerIp);
                IPEndPoint address = new IPEndPoint(ipAddress, ConstParameters.TransferListenPort);
                socket.Connect(address);
                socket.NoDelay = true;
                List<byte> mBytes = new List<byte>();

                mBytes.AddRange(BitConverter.GetBytes(messageId).Reverse());
                mBytes.AddRange(CommonRoutine.BcdStringToBytes(phoneNum.PadLeft(12, '0')));
                IPAddress localIp = ((IPEndPoint)(socket.LocalEndPoint)).Address;
                mBytes.AddRange(localIp.GetAddressBytes());
                mBytes.AddRange(messageBody);
                byte[] messageHead = OperateAgreement.GetMessageHead(ConstParameters.CmdRetweetTaxiDispatchClient, false, false, mBytes.ToArray().Length, new byte[6], new byte[2], 0, 0);
                byte[] sendData = OperateAgreement.PackageSendData(messageHead, mBytes.ToArray());
                socket.Send(sendData);
                Thread.Sleep(100);
                socket.ReceiveTimeout = 5000;

                byte[] receData = new byte[100];
                int receDatacount = socket.Receive(receData);
 
                if (receDatacount >= ConstParameters.MhLenth)
                {
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                return false;
            }

        }

        private void barButtonItem19_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //断电
            if (XtraMessageBox.Show("确定向该出租车发送断电命令？", "警告：", MessageBoxButtons.YesNo)
                == DialogResult.Yes)
            {
                XtraMessageBox.Show("断电命令发送成功！");
            }
        }

        //查看当前车辆的报警记录
        private void barButtonItem20_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //报警记录
            if (_drCurrentClickTaxiInfo != null)
            {
                TaxiWarmingHistoryForm warmingHistory =
                    new TaxiWarmingHistoryForm(_drCurrentClickTaxiInfo);
                warmingHistory.ShowDialog();
            }
            else
            {
                XtraMessageBox.Show("该出租车信息以及不存在，请重新刷新列表");
            }
        }

        //根据用户所在组设置权限
        private void SetMenuItemsEnableByPermission()
        {
            //if (UserName == "admin")
            //{               
            //    return;
            //}               
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.AudioMgrForm + "|"))
            {
                barBtn_AudioMgrForm.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.CallForTaxiForm + "|"))
            {
                barBtn_CallForTaxiForm.Enabled = true;
                barBtn_CallForTaxiForm2.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.CallRecordsForm + "|"))
            {
                barBtn_CallRecordsForm.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.ComplaintForm + "|"))
            {
                barBtn_ComplaintForm.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.DriverForm + "|"))
            {
                barBtn_DriverForm.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.GmapOverlayManagementForm + "|"))
            {
                barBtn_GmapOverlayManagementForm.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.ImageForm + "|"))
            {
                barBtn_ImageForm.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.NewsPushForm + "|"))
            {
                barBtn_NewsPushForm.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.PhoneUserForm + "|"))
            {
                barBtn_PhoneUserForm.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.TaxiCotrolForm + "|"))
            {
                barBtn_TaxiCotrolForm.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.TaxiFrom + "|"))
            {
                barBtn_TaxiFrom.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.TaxiGpsHistoryForm + "|"))
            {
                barBtn_TaxiGpsHistoryForm.Enabled = true;
                barBtn_TaxiGPSHistoryForm2.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.TaxiGroupForm + "|"))
            {
                barBtn_TaxiGroupForm.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.TaxiSetRectForm + "|"))
            {
                barBtn_TaxiSetRectForm.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.TaxiStateStatisticsReportForm + "|"))
            {
                barBtn_TaxiStateStatisticsReportForm.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.TradeHistoryForm + "|"))
            {
                barBtn_TradeHistoryForm.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.TransferServerIpSetForm + "|"))
            {
                barBtn_TransferServerIpSetForm.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.UserForm + "|"))
            {
                barBtn_UserForm.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.RoleManagementForm + "|"))
            {
                barBtn_RoleManagementForm.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.TaxiWarmingHistoryForm + "|"))
            {
                barBtn_TaxiWarmingHistoryForm.Enabled = true;
                barBtn_TaxiWarmingHistoryForm2.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.TaxiParameterSetForm + "|"))
            {
                barBtn_TaxiParameterSetForm.Enabled = true;
                barBtn_TaxiParameterSetForm2.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.TaxiBreakOilPowerOffCmd + "|"))
            {
                barBtn_SendBreakOilCmd.Enabled = true;
                barBtn_SendPowerOffCmd.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.TaxiServerSetForm + "|"))
            {
                barBtn_TaxiServerSetForm.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.ServerConfigManagementForm + "|"))
            {
                barBtn_ServerConfigManagementForm.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.AdMachineMainForm + "|"))
            {
                barBtn_AdMachineManagement.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.ShowPrivateCar + "|"))
            {
                barEditItem_showPrivateCar.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.PrivateCarForm + "|"))
            {
                barBnItem_PrivateCarForm.Enabled = true;
                
            }
          

            if (MyUserInfo.Permission.Contains("|" + PowerConfig.TaxiOnlineTimeForm + "|"))
            {
                barBtnItem_TaxiOnlineTimeForm.Enabled = true;
            }

            if (MyUserInfo.Permission.Contains("|" + PowerConfig.CompanyForm + "|"))
            {
                barBtnItem_CompanyForm.Enabled = true;
            }

            if (MyUserInfo.Permission.Contains("|" + 
                PowerConfig.TaxiRouteHistoryForm + "|"))
            {
                barBtnItem_TaxiRouteHistoryForm.Enabled = true;
            }
            
              if (MyUserInfo.Permission.Contains("|" + 
                PowerConfig.TaxiRouteStatisticsListForm + "|"))
            {
                barBtnItem_TaxiRouteStatisticsListForm.Enabled = true;
                barBtnItem_TaxiRouteStatisticsListForm.Enabled = true;
            }

            if (MyUserInfo.Permission.Contains("|" + 
                PowerConfig.TaxiChargeConfigSetForm + "|"))
            {
                barBtnItem_TaxiChargeConfigSetForm.Enabled = true;
            }

             if (MyUserInfo.Permission.Contains("|" + 
                PowerConfig.NoPsgConfigSet + "|"))
            {
                barBtnItem_NoPsgConfigSet.Enabled = true;
            }

             if (MyUserInfo.Permission.Contains("|" + 
                PowerConfig.PhoneMonitorForm + "|"))
            {
                barBtn_PhoneMonitorForm.Enabled = true;
            }

            if (MyUserInfo.Permission.Contains("|"+
                PowerConfig.PhoneUserMenu+"|"))
            {
                barSubItem_PhoneUserMenu.Enabled = true;
            }
            
            if (MyUserInfo.Permission.Contains("|" +
                PowerConfig.PrivateCarUserMenu + "|"))
            {
                barSubItem_privateCarMenu.Enabled = true;
            }

            if (MyUserInfo.Permission.Contains("|" +
                PowerConfig.SpecialCarForm + "|"))
            {
                barBtnItem_SpecialCarForm.Enabled = true;
            }


            if (MyUserInfo.Permission.Contains("|" +
                PowerConfig.CardCheckHistoryForm + "|"))
            {
                barBtnItem_CardCheckHistoryForm.Enabled = true;
            }

            if (MyUserInfo.Permission.Contains("|" +
                PowerConfig.AllowCheckShowSpecialCall + "|"))
            {

                barEditItem_showAmbulance.EditValue = true;
                _isShowSpecialCar = true;      
                barEditItem_showAmbulance.Enabled = true;
                btn_woundedList.Visible = true;
            }
         
            if (MyUserInfo.Permission.Contains("|" +
             PowerConfig.TaxiOfCdmaForm + "|"))
            {
                barBtnItem_TaxiOfCdmaForm.Enabled = true;
            }

            if (MyUserInfo.CompanyName.Contains("稳得福"))
            {
                barBtnItem_wendefu.Enabled = true;
            }
          

        }

        //查看当前车辆的历史轨迹
        private void barBtn_TaxiGPSHistoryForm2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (_drCurrentClickTaxiInfo != null)
            {
                TaxiGPSHistoryForm gpsHistoryForm = new TaxiGPSHistoryForm(
                    _drCurrentClickTaxiInfo);
                gpsHistoryForm.ShowDialog();
            }
            else
            {
                XtraMessageBox.Show("该出租车信息以及不存在，请重新刷新列表");
            }
        }

        //向该出租车电话招车
        private void barBtn_CallForTaxiForm2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (_drCurrentClickTaxiInfo != null)
            {
                DataTable dtTaxilist = _dtTaxiList.Clone();
                dtTaxilist.ImportRow(_drCurrentClickTaxiInfo);

                CallForTaxiForm callForTaxiForm = new CallForTaxiForm(dtTaxilist);
                callForTaxiForm.ShowDialog();
            }
            else
            {
                XtraMessageBox.Show("该出租车信息以及不存在，请重新刷新列表");
            }

        }

        private void barBtn_TaxiParameterSetForm_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            TaxiParametersSetForm taxiParameterSet = new TaxiParametersSetForm();
            taxiParameterSet.ShowDialog();
        }

        private void barBtn_TaxiParameterSetForm2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (_drCurrentClickTaxiInfo != null)
            {
                string taxiId = _drCurrentClickTaxiInfo["出租车ID"].ToString();
                TaxiParameterSetForm taxiParameterSet =
                    new TaxiParameterSetForm(int.Parse(taxiId));
                taxiParameterSet.ShowDialog();
            }
            else
            {
                XtraMessageBox.Show("该出租车信息以及不存在，请重新刷新列表");
            }

        }

        private void barBtn_ChangePassWordForm_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ChangePassWordForm changePassWordForm = new ChangePassWordForm();
            changePassWordForm.ShowDialog();
        }

        private void barBtn_CallPassengerForm_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            CallPassengerForm callpsg = new CallPassengerForm();
            callpsg.ShowDialog();
        }

        private void barBtn_PhoneMonitorForm_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            
            if (_drCurrentClickTaxiInfo != null)
            {
                string phoneNumber = _drCurrentClickTaxiInfo["司机号码"].ToString();
                PhoneMonitorForm monitorForm = new PhoneMonitorForm(phoneNumber);
                monitorForm.ShowDialog();
            }
            else
            {
                XtraMessageBox.Show("该出租车信息以及不存在，请重新刷新列表");
            }

        }

        private void barBtn_ServerConfigManagementForm_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ServerConfigManagementForm serverConfigManagement = new ServerConfigManagementForm();
            serverConfigManagement.ShowDialog();
        }

        private void barBtn_TaxiServerSetForm_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            TaxiServerSetForm taxiServerSetForm = new TaxiServerSetForm();
            taxiServerSetForm.ShowDialog();
        }

        private void barBtn_AdMachineManagement_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            AdMachineMainForm adMachineMainForm = new AdMachineMainForm();
            adMachineMainForm.ShowDialog();
        }

        
        private DataTable GetGridBindDt()
        {
            DataTable dt = _dtTaxiList.Copy();
            if (!_isShowPrivateCar)
            {
                string conditon = "车辆类型 <>'" +
                       ConstParameters.CarTypeOfPrivate + "'";
                DataRow[] rows = _dtTaxiList.Select(conditon);
                dt.Clear();
                foreach (DataRow dataRow in rows)
                {
                    dt.Rows.Add(dataRow.ItemArray);
                } 
            }
            
            // dt.DefaultView.Sort = "车辆类型 desc";
            DataView dv = dt.DefaultView;
            dv.Sort = "车辆类型 asc";
            if (_strSelectedCompany != "")
            {
                dv.Sort = "经度 desc";
            }
            return dv.Table;
            
        }

        private void gridView1_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            int index = e.RowHandle;
            if (index<0)
            {
                return;
            }
            DataRow row = gridView1.GetDataRow(index);
            if (row==null)
            {
                return;
            }
            int carType = int.Parse(row["车辆类型"].ToString());
            switch (carType)
            {
                case ConstParameters.CarTypeOfPrivate:
                        e.Appearance.ForeColor = Color.Blue;// 改变行字体颜色                
                        e.Appearance.BackColor = Color.LightYellow;// 改变行背景颜色                
                        //e.Appearance.BackColor2 = Color.Blue;// 添加渐变颜色
                    break;
                //case ConstParameters.CarTypeOfTaxi:
                //    e.Appearance.ForeColor = Color.DimGray;// 改变行字体颜色                
                //    break;
                
            }
            string state = row["出租车状态"].ToString();
            if (state == "未上线")
            {
                e.Appearance.BackColor = Color.LightGray;
            }
        }

        private void barBnItem_PrivateCarForm_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            PrivateCarForm form = new PrivateCarForm();
            form.ShowDialog();
        }

        private void barBtnItem_TaxiOnlineTimeForm_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            TaxiOnlineTimeForm form = new TaxiOnlineTimeForm();
            form.ShowDialog();
        }

        private void barBtnItem_TaxiRouteHistoryForm_ItemClick(object sender, ItemClickEventArgs e)
        {
            TaxiRouteHistoryForm form = new TaxiRouteHistoryForm();
            form.ShowDialog();
        }

        private void barBtnItem_NoPsgConfigSet_ItemClick(object sender, ItemClickEventArgs e)
        {
           

            if (_drCurrentClickTaxiInfo != null)
            {
                string phoneNumber = _drCurrentClickTaxiInfo["司机号码"].ToString();
                TaxiNoPsgConfigSetForm form = new TaxiNoPsgConfigSetForm(phoneNumber);
                form.ShowDialog();
            }
            else
            {
                XtraMessageBox.Show("该出租车信息以及不存在，请重新刷新列表");
            }
        }

        private void barBtnItem_TaxiRouteHistoryForm2_ItemClick(object sender, ItemClickEventArgs e)
        {
            TaxiRouteStatisticsListForm form = new TaxiRouteStatisticsListForm();
            form.ShowDialog();
        }

        private void barBtnItem_TaxiChargeConfigSetForm_ItemClick(object sender, ItemClickEventArgs e)
        {
            TaxiChargeConfigSetForm form = new TaxiChargeConfigSetForm();
            form.ShowDialog();
        }

        private void barBtnItem_CompanyForm_ItemClick(object sender, ItemClickEventArgs e)
        {
            CompanyForm form = new CompanyForm();
            form.ShowDialog();
        }

        private void barBtnItem_PhoneUserAreaStatisticsForm_ItemClick(object sender, ItemClickEventArgs e)
        {
            PhoneUserAreaStatisticsForm form = new PhoneUserAreaStatisticsForm(0);
            form.Show(this);
        }

        private void barBtnItem_AreaStatistics_ItemClick(object sender, ItemClickEventArgs e)
        {
            PhoneUserAreaStatisticsForm form = new PhoneUserAreaStatisticsForm(1);
            form.Show(this);
        }

        private void barBtnItem_SpecialCarForm_ItemClick(object sender, ItemClickEventArgs e)
        {
            SpecialCarForm form = new SpecialCarForm();
            form.ShowDialog();
        }



        private GMapRoute DrawrouteBetweenTowPoint(PointLatLng startPoint,
          PointLatLng endPoint, GMapOverlay overlay, string routeName)
        {
            if ((startPoint.Lat==0&&startPoint.Lng==0)
                ||(endPoint.Lat==0&&endPoint.Lng==0))
            {
                return null;
            }
            switch (_drawRouteType)
            {
                //case "1":
                //    break;
                case "2":
                        List<PointLatLng> points = new List<PointLatLng>();
                        points.Add(startPoint);
                        points.Add(endPoint);
                        GMapRoute r1 = new GMapRoute(points,routeName);
                        r1.Stroke = new Pen(Color.Green, 1);
                        overlay.Routes.Add(r1);
                        return r1;
                    break;
                default:
                        RoutingProvider rp = MainMap.MapProvider as RoutingProvider;
                        if (rp != null)
                        {
                            rp = GMapProviders.GoogleMap;
                        }
                        MapRoute route = rp.GetRoute(startPoint, endPoint,
                            false, false, (int)MainMap.Zoom);
           
                        if (route != null)
                        {
                            route.Name = routeName;
                            GMapRoute r = new GMapRoute(route.Points, route.Name);
                            overlay.Routes.Add(r);
                            //   gMap.ZoomAndCenterRoute(r);
                            return r;
                        }
                        return null;
                    break;
            }
        }


        #region 两点画线路/直线方法
        //画出两点之间的线路
        //private GMapRoute DrawrouteBetweenTowPoint(PointLatLng startPoint, 
        //    PointLatLng endPoint,GMapOverlay overlay, string routeName)
        //{
        //    RoutingProvider rp = MainMap.MapProvider as RoutingProvider;
        //    if (rp != null)
        //    {
        //        rp = GMapProviders.GoogleMap;
        //    }
        //    MapRoute route = rp.GetRoute(startPoint, endPoint,
        //        false, false, (int)MainMap.Zoom);
           
        //    if (route != null)
        //    {
        //        route.Name = routeName;
        //        GMapRoute r = new GMapRoute(route.Points, route.Name);
        //        overlay.Routes.Add(r);
        //        //   gMap.ZoomAndCenterRoute(r);
        //        return r;
        //    }
        //    return null;
        //}

        ////画出两点直接的直线
        //private GMapRoute DrawLineBetweenTwoPoint(PointLatLng startPoint,
        //    PointLatLng endPoint, GMapOverlay overlay, string routeName)
        //{
        //    List<PointLatLng> points = new List<PointLatLng>();
        //    points.Add(startPoint);
        //    points.Add(endPoint);
        //    GMapRoute r = new GMapRoute(points,routeName);
        //    r.Stroke = new Pen(Color.Green, 1);
        //    overlay.Routes.Add(r);
        //    return r;
        //}
        #endregion


        private PointLatLng _rightClickLatLng;
        private void barBtnItem_addWounded_ItemClick(object sender, ItemClickEventArgs e)
        {
             
            #region 弹出小窗口添加  注销
            AddWoundedForm form = new AddWoundedForm(_rightClickLatLng.Lng,
                _rightClickLatLng.Lat);
            form.ShowDialog();
            if (form.DialogResult == DialogResult.Yes)
            {
                GMapRoute oldRoute =
                _overlayOfPassenger.Routes.FirstOrDefault(
                  route => route.Name == form.Passenger.PhoneNumber);
                if (oldRoute != null)
                {
                    _overlayOfPassenger.Routes.Remove(oldRoute);
                }
                GMapMarker oldMarker =
                   _overlayOfPassenger.Markers.FirstOrDefault(
                   marker => marker.Tag.ToString()
                     == form.Passenger.PhoneNumber);
                if (oldMarker != null)
                {
                    _overlayOfPassenger.Markers.Remove(oldMarker);
                }

                Bitmap woundedObj = (Bitmap)TaxiState.wounded_1;
                PointLatLng woundedPoint = new PointLatLng(
                    form.Passenger.Lat, form.Passenger.Lng);
                WoundedMarker wounded = new WoundedMarker(woundedPoint, woundedObj,
                    form.Passenger.Name)
                {
                    ToolTipText =
                        "伤员信息" + Environment.NewLine
                        +"姓名："+form.Passenger.Name+Environment.NewLine
                        + "伤员电话：" + form.Passenger.PhoneNumber + Environment.NewLine
                        + "约定救护车手机号：" + form.Passenger.CarPhoneNumber + Environment.NewLine
                        + "伤员所在位置经度：" + form.Passenger.Lng + Environment.NewLine
                        + "伤员所在位置纬度：" + form.Passenger.Lat + Environment.NewLine
                        + "呼叫车辆时间：" + DateTime.Now,

                    ToolTipMode = MarkerTooltipMode.OnMouseOver,
                    Tag = form.Passenger.PhoneNumber
                };
                

                wounded.ToolTip.Format.Alignment = StringAlignment.Near;
                 
                _overlayOfPassenger.Markers.Add(wounded);
                //Thread t = new Thread(LightMarker);
                //t.IsBackground = true;
                //t.Start(wounded);

                GMapMarker taxiMarker =
                 _taxis.Markers.FirstOrDefault(
                 marker => marker.Tag.ToString()
                   == form.Passenger.CarPhoneNumber);
                if (taxiMarker != null)
                {
                    GMapRoute r = DrawrouteBetweenTowPoint(new PointLatLng(
                       taxiMarker.Position.Lat, taxiMarker.Position.Lng),
                       new PointLatLng(form.Passenger.Lat, form.Passenger.Lng),
                       _overlayOfPassenger,
                       form.Passenger.PhoneNumber);
                }

            }
            #endregion
        }

        //private void LightMarker(object objmarker)
        //{
        //    WoundedMarker marker = objmarker as WoundedMarker;
        //    for (int i = 0; i < 6; i++)
        //    {
        //        if (i % 2 == 0)
        //        {
        //            marker.Bitmap = TaxiState.wounded;
        //        }
        //        else
        //        {
        //            marker.Bitmap = TaxiState.wounded_1;
        //        }
        //        GMapMarker oldmarker;
        //        try
        //        {
        //            lock (_overlayOfPassenger.Markers)
        //            {
        //                oldmarker = _overlayOfPassenger.Markers.FirstOrDefault(
        //                    temp => temp.Tag.ToString() == marker.Tag.ToString());
        //                if (oldmarker != null)
        //                {
        //                    BeginInvoke(new MethodInvoker(() =>
        //                        _overlayOfPassenger.Markers.Remove(oldmarker)));

        //                }
        //                BeginInvoke(new MethodInvoker(() =>
        //                _overlayOfPassenger.Markers.Add(marker)));
        //            }
        //        }
        //        catch (Exception ex)
        //        {

        //        }

        //        Thread.Sleep(300);
        //    }
        //}


        private void MainMap_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                //_rightClickLatLng = MainMap.FromLocalToLatLng(e.X, e.Y);
                //popupMenu_mapRightDouble.ShowPopup(Cursor.Position);
            }
            else
            {

                if (e.Button == MouseButtons.Left)
                {
                    RectLatLng rect = MainMap.SelectedArea;
                    if (rect.Lat != 0 && rect.Lng != 0)
                    {
                        popupMenu_mapRightSingle.ShowPopup(Cursor.Position);
                    }
                }
            }
        }

        private void barBtnItem_wendefu_ItemClick(object sender, ItemClickEventArgs e)
        {
            WendefuForm form = new WendefuForm();
            form.ShowDialog();
          
        }

        private void barBtnItem_delWounded_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (_drCurrentPassenger != null)
            {
                if (XtraMessageBox.Show("是否确定删除该伤员?","警告：",
                    MessageBoxButtons.YesNo)== DialogResult.No)
                {
                    return;
                }
                string phoneNumber = _drCurrentPassenger["伤员号码"].ToString();
                PositionService.DeletePassengerByClient(phoneNumber);
                GMapMarker psgMarker = _overlayOfPassenger.Markers.FirstOrDefault(
                    marker => marker.Tag.ToString() == phoneNumber);
                if (psgMarker!=null)
                {
                    _overlayOfPassenger.Markers.Remove(psgMarker);
                }
                GMapRoute carRoute = _overlayOfPassenger.Routes.FirstOrDefault(
                    route => route.Name == phoneNumber);
                if (carRoute!=null)
                {
                    _overlayOfPassenger.Routes.Remove(carRoute);
                }
                GMapRoute destRoute = _overlayOfDestination.Routes.FirstOrDefault(
                   route => route.Name == phoneNumber);
                if (destRoute != null)
                {
                    _overlayOfDestination.Routes.Remove(destRoute);
                }
                XtraMessageBox.Show("该伤员已删除！");
            }
            else
            {
                XtraMessageBox.Show("该伤员所约定的救护车已经不存在，请重新刷新列表！");
            }
        }

        private void barBtnItem_setToWounded_ItemClick(object sender, ItemClickEventArgs e)
        {
            string carPhoneNum = _drCurrentClickTaxiInfo["司机号码"].ToString();
            string psgPhoneNum = _drCurrentPassenger["伤员号码"].ToString();
            int result = PositionService.SetPassengerToCar(carPhoneNum,
            ConstParameters.CarTypeOfAmbulance, psgPhoneNum);
            switch (result)
            {
                case 0 :
                    XtraMessageBox.Show("该车已下线！");
                    break;
                case 1:
                    //成功                    
                    GMapMarker taxiMarker = _taxis.Markers.FirstOrDefault(
                        taxi => taxi.Tag.ToString() == carPhoneNum);
                    GMapMarker psgMarker = _overlayOfPassenger.Markers.FirstOrDefault(
                        psg => psg.Tag.ToString() == psgPhoneNum);
                    GMapRoute oldRoute = _overlayOfPassenger.Routes.FirstOrDefault(
                        route => route.Name == psgPhoneNum);
                    if (oldRoute!=null)
                    {
                        _overlayOfPassenger.Routes.Remove(oldRoute);
                    }
                    GMapRoute newRoute = DrawrouteBetweenTowPoint(taxiMarker.Position,
                     psgMarker.Position, _overlayOfPassenger,psgPhoneNum);
                    _drCurrentPassenger = null;
                    break;
                case 2:
                    XtraMessageBox.Show("服务器未找到该伤员信息，请核对或重新添加！");
                    break;
                case 3:
                    XtraMessageBox.Show("该车辆类型错误，该车不为救护车！");
                    break;
            }

        }

        private void barBtn_addHospital_ItemClick(object sender, ItemClickEventArgs e)
        {
            PointLatLng point = _rightClickLatLng;
            AddDestinationForm addDestForm = new AddDestinationForm(point.Lng,
                point.Lat);
            addDestForm.ShowDialog();

            if (addDestForm.DialogResult == DialogResult.Yes
                && addDestForm.DestInfo!=null)
            {
               
                Bitmap obj = TaxiState.hospital_1;
                HospitalMarker gmarker = new HospitalMarker(point, obj,
                    addDestForm.DestInfo.Name);
                gmarker.Tag = addDestForm.DestInfo.Id;

                _overlayOfDestination.Markers.Add(gmarker);
                if (_drCurrentClickTaxiInfo != null)
                {
                    string phone = _drCurrentClickTaxiInfo["司机号码"].ToString();
                    string carType = _drCurrentClickTaxiInfo["车辆类型"].ToString();
                    if ((byte)int.Parse(carType) ==
                        ConstParameters.CarTypeOfAmbulance)
                    {
                        int result =
                            PositionService.SetDestinationId(
                            ConstParameters.TypePhoneUser, phone,
                            addDestForm.DestInfo.Id);
                        if (result == 1)
                        {
                            double lng = double.Parse(
                                _drCurrentClickTaxiInfo["纬度"].ToString());
                            double lat = double.Parse(
                                _drCurrentClickTaxiInfo["经度"].ToString());
                            GMapRoute route =
                            DrawrouteBetweenTowPoint(new PointLatLng(lat, lng),
                            point, _overlayOfDestination, phone);
                        }
                    }
                }
            }


            
            //DestinationInfo model = new DestinationInfo();
            //model.Lat = point.Lat;
            //model.Lng = point.Lng;
            //model.Type = ConstParameters.CarTypeOfAmbulance;            
          
 
        }

        private void barBtnItem_clearHospital_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (_drCurrentDestination==null)
            {
                return;
            }
            if (XtraMessageBox.Show("是否确定删除该医院?","警告：",MessageBoxButtons.YesNo)
                == DialogResult.No)
            {
                return;
            }
            int id = int.Parse(_drCurrentDestination["Id"].ToString());
            PositionService.DeleteDestinationById(id);
            GMapMarker hopital = _overlayOfDestination.Markers.FirstOrDefault(
                marker => marker.Tag.ToString() == id.ToString());
            if (hopital!=null)
            {
                _overlayOfDestination.Markers.Remove(hopital);
            }
            //清除该医院相关乘客之间的路线
            DataTable dt = _dtPassengerList.Copy();
            foreach (DataRow row in dt.Rows)
            {
                int destid = int.Parse(row["目的地ID"].ToString());
                string phone = row["伤员号码"].ToString();
                if (destid==id)
                {
                    GMapRoute hosRoute = _overlayOfDestination.Routes.FirstOrDefault(
                        route => route.Name == phone);
                    if (hosRoute!=null)
                    {
                        _overlayOfDestination.Routes.Remove(hosRoute);    
                    }                    
                }
            }             
        }

        private void SendDestination(object obj)

        {
            DataRowAndStringInfo dataInfo = obj as DataRowAndStringInfo;
            DataRow row = dataInfo.Row;
            string phoneNum = dataInfo.StrValue;
            int type = int.Parse(row["类型"].ToString());
            string name = row["名称"].ToString();
            double lat = double.Parse(row["纬度"].ToString());
            double lng = double.Parse(row["经度"].ToString());
            DataTransCommon dataTrans = new DataTransCommon();

            //dataTrans.SendDestinationInfoData((byte) type,
            //    lng, lat, name, phoneNum);
             
            DateTime startTime = DateTime.Now;
            byte[] receData;
            do
            {
                receData = dataTrans.SendDestinationInfoData((byte)type,
                lng, lat, name, phoneNum);
                Thread.Sleep(3000);
            }
            while (receData == null &&
               (DateTime.Now - startTime).Minutes < 5);
        }

        private class DataRowAndStringInfo
        {
            public DataRow Row;
            public string StrValue;
        }


        private void SendPassengerInfo(object obj)
        {
            DataRowAndStringInfo dataInfo = obj as DataRowAndStringInfo;
            DataRow row = dataInfo.Row;
            string phone = row["伤员号码"].ToString();
            double lat = double.Parse(row["纬度"].ToString());
            double lng = double.Parse(row["经度"].ToString());
            DataTransCommon dataTrans = new DataTransCommon();
           // dataTrans.SendPassengerInfoData(phone, lng, lat, dataInfo.StrValue);
             
            DateTime startTime = DateTime.Now;
            byte[] receData;
            do
            {
                receData = dataTrans.SendPassengerInfoData(
                    phone, lng, lat, dataInfo.StrValue);
                Thread.Sleep(3000);
            }
            while (receData == null &&
               (DateTime.Now - startTime).Minutes < 5);             
        }

        private void SendCarInfo(object obj)
        {
            DataRowAndStringInfo dataInfo = obj as DataRowAndStringInfo;
            DataRow row = dataInfo.Row;

            //DataTransCommon dataTrans = new DataTransCommon();
            //dataTrans.SendCarInfoData(4, "15555215554", 114.40463, 30.47577,
            //                          dataInfo.StrValue);
            //dataTrans.SendDestinationInfoData(4, 114.404153, 30.47377, "挖掘机",
            //                         dataInfo.StrValue);

            //return;

            string phone = row["司机号码"].ToString();
            double lng = double.Parse(row["纬度"].ToString());
            double lat = double.Parse(row["经度"].ToString());
            int type = int.Parse(row["车辆类型"].ToString());
            DataTransCommon dataTrans = new DataTransCommon();
            //dataTrans.SendCarInfoData((byte)type, phone, lng, lat,
            //    dataInfo.StrValue);

            DateTime startTime = DateTime.Now;

            byte[] receData;
            do
            {
                receData = dataTrans.SendCarInfoData(
                (byte)type, phone, lng, lat, dataInfo.StrValue);
                Thread.Sleep(3000);
            }
            while (receData == null &&
               (DateTime.Now - startTime).Minutes < 5);
        }
         
        private void barBtnItem_setAmbu_ItemClick_1(object sender, ItemClickEventArgs e)
        {
            if (_drCurrentPassenger==null)
            {
                return;
            }
            try
            {
                string psgPhone = _drCurrentPassenger["伤员号码"].ToString();
                double psgLng = double.Parse(_drCurrentPassenger["经度"].ToString());
                double psgLat = double.Parse(_drCurrentPassenger["纬度"].ToString());
                int psgDestId = int.Parse(_drCurrentPassenger["目的地ID"].ToString());

                DataTable dtcopy = _dtTaxiList.Copy();
                DataRow[] cars = dtcopy.Select("车辆类型 ="
                 + ConstParameters.CarTypeOfAmbulance);
                DataTable dt = dtcopy.Clone();

                foreach (DataRow row in cars)
                {
                    if (row["伤员号码"].ToString() == "")
                    {
                        dt.Rows.Add(row.ItemArray);
                    }
                }
                ListOfCarForm listform = new ListOfCarForm(dt);
                listform.ShowDialog();
                if (listform.DialogResult == DialogResult.Yes)
                {
                    DataRow row = listform.SelectedRow;
                    if (row != null)
                    {
                        string carPhone = row["司机号码"].ToString();
                        double lng = double.Parse(row["纬度"].ToString());
                        double lat = double.Parse(row["经度"].ToString());
                        int carDestId = int.Parse(row["目的地ID"].ToString());
                        PositionService.SetPassengerToCar(carPhone,
                        ConstParameters.CarTypeOfAmbulance, psgPhone);
                        GMapRoute oldRoute = _overlayOfPassenger.Routes.FirstOrDefault(
                            temp => temp.Name == psgPhone);
                        if (oldRoute != null)
                        {
                            _overlayOfPassenger.Routes.Remove(oldRoute);
                        }
                        DrawrouteBetweenTowPoint(new PointLatLng(
                        psgLat, psgLng), new PointLatLng(lat, lng),
                        _overlayOfPassenger, psgPhone);

                        //_markerCurrentCar.ToolTipMode = MarkerTooltipMode.OnMouseOver;


                        //发送乘客信息给司机
                        DataRowAndStringInfo psgInfo = new DataRowAndStringInfo();
                        DataRow psgRow = _drCurrentPassenger;
                        psgInfo.Row = psgRow;
                        psgInfo.StrValue = carPhone;
                        Thread t = new Thread(SendPassengerInfo);
                        t.IsBackground = true;
                        t.Start(psgInfo);

                        //发送司机信息给乘客
                        DataRowAndStringInfo carInfo = new DataRowAndStringInfo();
                        DataRow carRow = row;
                        carInfo.Row = carRow;
                        carInfo.StrValue = psgPhone;
                        Thread t2 = new Thread(SendCarInfo);
                        t2.IsBackground = true;
                        t2.Start(carInfo);



                        int destId = 0;
                        if (carDestId != 0)
                        {
                            destId = carDestId;
                        }
                        else
                        {
                            if (psgDestId != 0)
                            {
                                destId = psgDestId;
                            }
                        }
                        if (destId != 0)
                        {
                            //发送目的地消息到乘客                                        
                            DataTable dtTemp = _dtDestination.Copy();
                            DataRow[] destRows = dtTemp.Select("Id=" + destId);
                            if (destRows.Length == 0)
                            {
                                return;
                            }
                            DataRowAndStringInfo destInfo1 = new DataRowAndStringInfo();
                            destInfo1.Row = destRows[0];
                            destInfo1.StrValue = psgPhone;
                            Thread t3 = new Thread(SendDestination);
                            t3.IsBackground = true;
                            t3.Start(destInfo1);

                            //发送目的地到司机
                            DataRowAndStringInfo destInfo2 = new DataRowAndStringInfo();
                            destInfo2.Row = destRows[0];
                            destInfo2.StrValue = carPhone;
                            Thread t4 = new Thread(SendDestination);
                            t4.IsBackground = true;
                            t4.Start(destInfo2);
                        }

                       // _drCurrentPassenger = null;

                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
           
        }

        //为病员指定医院
        private void barButtonItem5_ItemClick_1(object sender, ItemClickEventArgs e)
        {
            if (_drCurrentPassenger == null)
            {
                return;
            }
            string psgPhone = _drCurrentPassenger["伤员号码"].ToString();
            double psgLng = double.Parse(_drCurrentPassenger["经度"].ToString());
            double psgLat = double.Parse(_drCurrentPassenger["纬度"].ToString());
            string carPhone = _drCurrentPassenger["约定车辆手机号"].ToString();
            DataTable dtcopy = _dtDestination.Copy();
            DataRow[] hospitals = dtcopy.Select("类型 ="
             + ConstParameters.CarTypeOfAmbulance);
            DataTable dt = dtcopy.Clone();         
            foreach (DataRow row in hospitals)
            {                
               dt.Rows.Add(row.ItemArray);               
            }
            ListOfDestinationForm listform = new ListOfDestinationForm(dt);
            listform.ShowDialog();

            if (listform.DialogResult == DialogResult.Yes)
            {
                DataRow row = listform.SelectedRow;
                if (row != null)
                {
                    int id = int.Parse(row["Id"].ToString());
                    double lng = double.Parse(row["经度"].ToString());
                    double lat = double.Parse(row["纬度"].ToString());
                
                    PositionService.SetDestinationId(1, psgPhone, id);
                    
                    GMapRoute oldRoute = _overlayOfDestination.Routes.FirstOrDefault(
                        temp => temp.Name == psgPhone);
                    if (oldRoute != null)
                    {
                        _overlayOfDestination.Routes.Remove(oldRoute);
                    }
                    DrawrouteBetweenTowPoint(new PointLatLng(
                    psgLat, psgLng), new PointLatLng(lat, lng),
                    _overlayOfDestination, psgPhone);



                    //发送目的地消息到乘客                                                              
                    DataRowAndStringInfo destInfo1 = new DataRowAndStringInfo();
                    destInfo1.Row = row;
                    destInfo1.StrValue = psgPhone;
                    Thread t3 = new Thread(SendDestination);
                    t3.IsBackground = true;
                    t3.Start(destInfo1);

                    if (carPhone!="")
                    {                        
                        //发送目的地到司机
                        DataRowAndStringInfo destInfo2 = new DataRowAndStringInfo();
                        destInfo2.Row = row;
                        destInfo2.StrValue = carPhone;
                        Thread t4 = new Thread(SendDestination);
                        t4.IsBackground = true;
                        t4.Start(destInfo2);
                    }
                    


                  //  _drCurrentPassenger = null;
                }
            }
        }


        //清除该救护车上的病员
        private void barBtnItem_clearWoundedIncar_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (_drCurrentClickTaxiInfo == null)
            {
                return;
            }
            string carPhone = _drCurrentClickTaxiInfo["司机号码"].ToString();
            string psgPhone = _drCurrentClickTaxiInfo["伤员号码"].ToString();
            if (psgPhone == "")
            {
                XtraMessageBox.Show("该车未指定病员！");
                return;
            }
            try
            {
                PositionService.ClearCarPassengerByClient(carPhone, psgPhone);
                GMapRoute route1 = _overlayOfPassenger.Routes.FirstOrDefault(
                    temp => temp.Name == psgPhone);
                if (route1 != null)
                {
                    _overlayOfPassenger.Routes.Remove(route1);
                }
                GMapRoute route2 = _overlayOfDestination.Routes.FirstOrDefault(
                    temp => temp.Name == psgPhone);
                if (route2 != null)
                {
                    _overlayOfDestination.Routes.Remove(route2);
                }
                _drCurrentPassenger = null;
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
            }           
        }

        //列表模式下为车辆指定病员
        private void barBtnItem_selectWounded_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        //向选中区域内的车辆发送消息
        private void barBtnItem_sendMsgToAreaCars_ItemClick(object sender, ItemClickEventArgs e)
        {
            RectLatLng rectLatLng = MainMap.SelectedArea;
            if (rectLatLng.Lat==0 && rectLatLng.Lng ==0)
            {
                XtraMessageBox.Show("尚未选取区域，请按住Shift键，拖动鼠标右键进行选取！");
                return;
            }
            DataTable dtCars = _dtTaxiList.Copy();
            DataTable dt = dtCars.Clone();            
            foreach (DataRow row in dtCars.Rows)
            {
                int carType = int.Parse(row["车辆类型"].ToString());
                double lat = double.Parse(row["经度"].ToString());
                double lng = double.Parse(row["纬度"].ToString());                
                if (   carType==ConstParameters.CarTypeOfTaxi 
                    && lat >= rectLatLng.LocationRightBottom.Lat
                    && lat <= rectLatLng.LocationTopLeft.Lat
                    && lng >= rectLatLng.LocationTopLeft.Lng
                    && lng <= rectLatLng.LocationRightBottom.Lng                
                    )
                {
                    dt.Rows.Add(row.ItemArray.ToArray());
                }
            }
            NewsPushForm newsPushForm = new NewsPushForm(dt);
            newsPushForm.ShowDialog();
        }

        private void barBtnItem_CardCheckHistoryForm_ItemClick(object sender, ItemClickEventArgs e)
        {
            CardCheckingHistoryForm form = new CardCheckingHistoryForm();
            form.ShowDialog();
        }

        private void panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void btn_woundedList_MouseClick(object sender, MouseEventArgs e)
        {
            string tag = btn_woundedList.Tag.ToString();
            if (tag=="0")
            {
                gridControl_wouded.DataSource = _dtPassengerList;
                gridControl_wouded.Visible = true;
                btn_freshWounded.Visible = true;
                btn_woundedList.Image = Resources.btn_RightArrow_Green_32x32;
                //btn_woundedList.BackColor = Color.FromArgb(201, 210, 226);
                btn_woundedList.Tag = "1";
            }
            else
            {
                gridControl_wouded.Visible = false;
                btn_freshWounded.Visible = false;
                btn_woundedList.Image = Resources.btn_LeftArrow_Green_32x32;
               // btn_woundedList.BackColor = Color.Transparent;
                btn_woundedList.Tag = "0";
            }
        }

        private void btn_freshWounded_MouseClick(object sender, MouseEventArgs e)
        { 
            gridControl_wouded.DataSource = null;
            gridControl_wouded.DataSource = _dtPassengerList;
           
        }

        private void gridView_wounded_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            DataRow row = gridView_wounded.GetDataRow(gridView_wounded.FocusedRowHandle);
            if (row!=null)
            {
                if (e.Button == MouseButtons.Right)
                {
                    #region

                    string phoneNumber = row["伤员号码"].ToString();                    
                    DataTable dtPsg = _dtPassengerList.Copy();
                    StringBuilder sbPsg = new StringBuilder();
                    sbPsg.Append("伤员号码='");
                    sbPsg.Append(phoneNumber);
                    sbPsg.Append("'");

                    DataRow[] drsPsg = dtPsg.Select(sbPsg.ToString());
                    _drCurrentPassenger = drsPsg.Length >=
                        1 ? drsPsg[0] : null;

                    if (_drCurrentPassenger == null)
                    {
                        return;
                    }
                    if (MyUserInfo.Permission.Contains("|" +
                           PowerConfig.AllowDispatchAmbulance + "|"))
                    {
                        popupMenu_woundedRight.ShowPopup(MousePosition);
                    }

                    #endregion
                }
                else
                {
                    double lat = double.Parse(row["纬度"].ToString());
                    double lng = double.Parse(row["经度"].ToString());
                    MainMap.Position = new PointLatLng(lat, lng);   
                }
                 
            }


           



        }

        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        private void btn_freshWounded_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
            btn_freshWounded.Image = Resources.btn_RefreshGreen_32x32_blue;
        }

        private void btn_freshWounded_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
            btn_freshWounded.Image = Resources.btn_RefreshGreen_32x32;
        }

       


        #region  For Test

        //TaxiInfo tempTaxiInfo = new TaxiInfo();
        //public AutoResetEvent DrawTaxiWait = new AutoResetEvent(false);
        //public AutoResetEvent GetTaxilInListWait = new AutoResetEvent(true);
        //private void DrawAllTaxiInfos()
        //{
        //    System.Diagnostics.Stopwatch myWatch = new System.Diagnostics.Stopwatch();
        //    myWatch.Start();
        //    List<TaxiInfo> taxiInfoList = PositionService.GetAllTaxiInfos();
        //    foreach (TaxiInfo taxiInfo in taxiInfoList)
        //    {
        //        GetTaxilInListWait.WaitOne();
        //        tempTaxiInfo = taxiInfo;
        //        DrawTaxiWait.Set();
        //    }
        //    myWatch.Stop();
        //    _timerPerf.Stop();
        //    Console.WriteLine("耗时：" + myWatch.ElapsedMilliseconds + "ms");
        //    MessageBox.Show("耗时：" + myWatch.ElapsedMilliseconds / 1000f + "s");
        //}



        //AddTaxiMarkers.Clear();
        //foreach (DictionaryEntry dictionaryEntry in TaxiList)
        //{
        //    if (!TaxiMarkersContainKey(dictionaryEntry.Key.ToString()))
        //    {
        //        TaxiInfo temp = (TaxiInfo)dictionaryEntry.Value;
        //        PointLatLng point = new PointLatLng(temp.Latitude, temp.Longitude);
        //        Bitmap obj = GetTaxiBitmap(temp.TaxiState);
        //        ArrayList al = new ArrayList { temp.DriverPhoneNumber, temp.TaxiState };
        //        GMarkerGoogle gMarker = new GMarkerGoogle(point, obj)
        //        {
        //            ToolTipText = Convert.ToString(temp.TaxiNo),
        //            ToolTipMode = MarkerTooltipMode.OnMouseOver,
        //            Tag = al
        //        };
        //        AddTaxiMarkers.Add(gMarker);
        //    }
        //}



        //private void DrawAllTaxisOnMap(object sender, EventArgs e)
        //{
        //    //lock (_taxis.Markers)
        //    {
        //        _taxis.Markers.Clear();
        //        _timerPerf.Interval = 10000;
        //        System.Diagnostics.Stopwatch myWatch = new System.Diagnostics.Stopwatch();
        //        myWatch.Start();
        //        List<TaxiInfo> taxiInfoList = PositionService.GetAllTaxiInfos();

        //        foreach (TaxiInfo taxiInfo in taxiInfoList)
        //        {
        //            PointLatLng point = new PointLatLng(taxiInfo.Latitude, taxiInfo.Longitude);
        //            Bitmap obj = GetTaxiBitmap(taxiInfo.TaxiState);
        //            GMarkerGoogle gMarker = new GMarkerGoogle(point, obj)
        //            {
        //                ToolTipText = Convert.ToString(taxiInfo.TaxiNo),
        //                ToolTipMode = MarkerTooltipMode.OnMouseOver,
        //                Tag = taxiInfo.DriverPhoneNumber
        //            };
        //            this.BeginInvoke(new MethodInvoker(() => _taxis.Markers.Add(gMarker)));
        //        }
        //        myWatch.Stop();
        //        _timerPerf.Stop();
        //        Console.WriteLine("耗时：" + myWatch.ElapsedMilliseconds + "ms");
        //        MessageBox.Show("耗时：" + myWatch.ElapsedMilliseconds + "ms");
        //    }
        //}



        //private void timer_Tick(object sender, EventArgs e)
        //{
        //    DrawTaxiWait.WaitOne();
        //    PointLatLng point = new PointLatLng(tempTaxiInfo.Latitude, tempTaxiInfo.Longitude);
        //    Bitmap obj = GetTaxiBitmap(tempTaxiInfo.TaxiState);
        //    GMarkerGoogle gMarker = new GMarkerGoogle(point, obj)
        //    {
        //        ToolTipText = Convert.ToString(tempTaxiInfo.TaxiNo),
        //        ToolTipMode = MarkerTooltipMode.OnMouseOver,
        //    };
        //    this.BeginInvoke(new MethodInvoker(() => _taxis.Markers.Add(gMarker)));


        //    GetTaxilInListWait.Set();

        //}

        //private bool TaxiMarkersContainKey(string key)
        //{
        //    lock (_taxis.Markers)
        //    {
        //        return _taxis.Markers.Any(gMapMarker => ((ArrayList)gMapMarker.Tag)[0].ToString() == key);
        //    }
        //}

        #endregion
    }
}